为什么attr_accessor揍在这种模式在Ruby on Rails的现有的变量?
-
11-09-2019 - |
题
我被这最近咬伤,并且它会是有用确切地知道发生了什么事要做到这一点,那么其他人避免这样的错误。
我有一个模型的用户,具有像这样的模式:
create_table "users", :force => true do |t|
t.string "user_name"
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "location"
t.string "town"
t.string "country"
t.string "postcode"
t.boolean "newsletter"
在类user.rb,我有三种方法attr_accessor:
class User < ActiveRecord::Base
# lots of code
attr_protected :admin, :active
# relevant accessor methods
attr_accessor :town, :postcode, :country
end
现在在我的用户控制器,如果我有下面的方法:
def create
@user = User.new params[:user]
end
当当我尝试创建与所述内容的新用户在此PARAMS散列:
--- !map:HashWithIndifferentAccess
# other values
country: United Kingdom
dob(1i): "1985"
dob(2i): "9"
dob(3i): "19"
town: london
返回的对象具有用于country
,town
和邮政编码postcode
值空字符串,像这样。
(rdb:53) y user1
--- !ruby/object:User
attributes:
# lots of attributes that aren't relevant for this example, and are filled in okay
postcode:
country:
town:
我可以告诉大家,attr_accessor中方法重挫活动记录现有的存取方法,因为当我带他们出去一切工作正常,因此该解决方案是非常简单的 - 只是把它们从
不过的什么的到底正在发生的时候,这里?
我期待在这里的 Rails的API文档的Active Record 和这里的红宝石自己约attr_accessor
的文档,但我仍然略显朦胧如何attr_accessor
这里摔东西
任何能够阐明一些停止的这一些其他灵魂差落入犯规?
解决方案
当您添加一个attr_accessor一类,它定义在其上,例如两个方法用户#邮政编码和用户#邮政编码=。
如果访问者的名字等于一个模型属性的名称,打破东西(如果你不小心)。当您指定属性的模型,用户#邮政编码=被调用,并在你的情况下,它什么都不做,除了
@postcode = value
所以此值只获取存储在一个实例变量并没有出现在属性散列。
而在正常情况下(没有访问),这会去的method_missing并最终引发类似
write_attribute(:postcode, value)
然后它就会出现在你的模型的属性。 希望是有道理的。
其他提示
为什么在第一个地方使用的是attr_accessor :town, :postcode, :country
?活动记录对你的setter / getter方法。刚落,那行,事情应该工作。
您可能想使用attr_accessible
上ActiveRecord的模型,使属性的质量分配。对模型属性的getter / setter方法已经被定义你不需要attr_accessor
。