Ruby on rails 为什么attr_访问器在rubyonrails中破坏了这个模型中现有的变量?
我最近被这件事咬了一口,准确地知道是什么让这件事发生是很有用的,这样其他人就可以避免这个错误 我有一个模型用户,模式如下:Ruby on rails 为什么attr_访问器在rubyonrails中破坏了这个模型中现有的变量?,ruby-on-rails,models,accessor,Ruby On Rails,Models,Accessor,我最近被这件事咬了一口,准确地知道是什么让这件事发生是很有用的,这样其他人就可以避免这个错误 我有一个模型用户,模式如下: 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.stri
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_访问器,用于三种方法:
class User < ActiveRecord::Base
# lots of code
attr_protected :admin, :active
# relevant accessor methods
attr_accessor :town, :postcode, :country
end
当我尝试使用此参数哈希中的内容创建新用户时:
--- !map:HashWithIndifferentAccess
# other values
country: United Kingdom
dob(1i): "1985"
dob(2i): "9"
dob(3i): "19"
town: london
返回的对象具有用于国家
、城镇
和邮政编码邮政编码
值的空字符串,如下所示
(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_访问器方法正在破坏activerecord现有的访问器方法,因为当我取出它们时,它们都可以正常工作,所以解决方案相当简单——只需取出它们即可
但在这里到底发生了什么
我在中查看这里,在中查看这里,但我仍然对attr\u accessor
是如何破坏这里的东西有点模糊
有没有人能透露一些信息来阻止另一个可怜的灵魂与此发生冲突?为什么首先要使用
attr\u访问器:town,:postcode,:country
?Active Record为您提供了setter/getter方法。只要去掉那一行,事情就应该可以了。当你向一个类添加属性访问器时,它定义了两个方法,例如User#postcode和User#postcode=
如果访问器的名称等于模型属性的名称,则情况会发生变化(如果不小心)。将属性指定给模型时,将调用User#postcode=,在您的情况下,它除了
@postcode = value
因此,该值只存储在实例变量中,而不会出现在属性散列中
而在正常情况下(没有访问器),这将导致方法_丢失,并最终触发类似的事件
write_attribute(:postcode, value)
然后它会出现在模型的属性中。
希望这是有意义的。您可能希望在ActiveRecord模型上使用
attr\u accessible
,以启用属性的批量分配。您不需要attr\u访问器
,因为已经为模型属性定义了getter/setter;已经搞定了。我想知道引擎盖下发生了什么。还有一个问题需要用clobber这个词。
write_attribute(:postcode, value)