Rails的属性头痛 [英] Rails attributes headache
本文介绍了Rails的属性头痛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
新手轨的问题上来。
我有一类这样的:
class Thing < ActiveRecord::Base
attr_accessible :name
attr_accessor :name
validates_uniqueness_of :name, :case_sensitive => false
end
我已经做了迁移和表没问题。然后,我火了轨控制台
和尝试以下操作:
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
为什么这个名字我指定不被保存? 我要的是能够调用new时指定的属性散列,然后保存该实例。
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.
推荐答案
您应该删除 attr_accessor:名称
,这个创建的getter和放大器; setter方法名称
,但他们已经创建的ActiveRecord的
You should remove attr_accessor :name
, this create getter & setter for name
, but they are already created by ActiveRecord
这篇关于Rails的属性头痛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文