Rails attributes headache

爱⌒轻易说出口 提交于 2020-01-02 20:10:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!