true do |-6ren">
gpt4 book ai didi

ruby-on-rails - 为什么 attr_accessor 会破坏 Ruby on Rails 中此模型中的现有变量?

转载 作者:行者123 更新时间:2023-12-04 07:37:25 25 4
gpt4 key购买 nike

我最近被这个问题困扰了,准确地知道发生了什么会很有用,这样其他人就可以避免这个错误。

我有一个模型用户,其架构如下:

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

现在在我的用户 Controller 中,如果我有以下方法:

def create
@user = User.new params[:user]
end

当我尝试使用此参数哈希中的内容创建新用户时:

  --- !map:HashWithIndifferentAccess 
# other values
country: United Kingdom
dob(1i): "1985"
dob(2i): "9"
dob(3i): "19"
town: london

返回的对象对于 countrytown 和 postcode 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 方法正在破坏 Active Record 现有的访问器方法,因为当我将它们移除时一切正常,所以解决方案非常简单 - 只需将它们移除。

但是 这里到底发生了什么?

我正在 Rails API docs for Active Record 中查看这里,这里是Ruby's own docs about attr_accessor ,但我对 attr_accessor 是如何破坏这里的东西仍然有些模糊。

任何人都能够阐明一些光来阻止其他可怜的灵魂犯下这个错误吗?

最佳答案

当您将 attr_accessor 添加到类时,它会在其上定义两个方法,例如User#postcode 和 User#postcode=。

如果访问器的名称等于模型属性的名称,事情就会中断(如果你不小心的话)。当您将属性分配给模型时, User#postcode= 被调用,在您的情况下它除了

之外什么都不做
@postcode = value

所以这个值只是存储在一个实例变量中,不会出现在属性散列中。

而在正常情况下(没有访问器)这将转到 method_missing 并最终触发类似的东西

write_attribute(:postcode, value)

然后它会出现在您模型的属性中。希望这是有道理的。

关于ruby-on-rails - 为什么 attr_accessor 会破坏 Ruby on Rails 中此模型中的现有变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1448414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com