问题
newbie rails question coming up.
I have a class like this:
class Thing < ActiveRecord::Base
attr_accessible :name
attr_accessor :name
validates_uniqueness_of :name, :case_sensitive => false
end
I have done a migration and the table looks okay. I then fire up the rails console
and try the following:
t = Thing.new(:name => "test")
=> #<Thing id: nil, name: nil, description: nil, created_at: nil, updated_at: nil>
already here it says name is nil, why? Continuing on, I try this:
t.name
=> "test"
Now name seems to be set anyway? If I try to save:
t.save!
Thing Exists (8.0ms) SELECT 1 AS one FROM "things" WHERE LOWER("things"."name") = LOWER('test') LIMIT 1
SQL (16.0ms) INSERT INTO "things" ("created_at", "description", "name", "updated_at") VALUES ('2012-10-28 16:10:12.701000', NULL, NULL, '2012-10-28 16:10:12.701000')
=> true
Why is the name I have specified not being saved? What I want is to be able to specify attributes as a hash when calling new and then save the instance.
回答1:
You should remove attr_accessor :name
, this create getter & setter for name
, but they are already created by ActiveRecord
来源:https://stackoverflow.com/questions/13110573/rails-attributes-headache