gpt4 book ai didi

ruby-on-rails-4 - Rails4 : How to trigger the callback for attr_accessor while using accepts_nested_attributes_for

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

请检查伪代码:

class Team
has_many :users
accepts_nested_attributes_for :users, allow_destroy: true
end

class User
belongs_to :team
has_many :addresses
accepts_nested_attributes_for :addresses
attr_accessor :dummy

before_validation :generate_addresses_attributes
def generate_addresses_attributes
# Use the dummy value to set the addresses_attributes
end
end

现在执行 team.update(users_attributes: [{"0" => { dummy: "changed!" }}]) (除了虚拟属性,其他字段不会改变),它不会触发#generate_addresses_attributes 回调,因为它认为没有任何变化,没有保存,没有回调......

所以我的问题是如何触发虚拟属性的回调,或者强制保存 accepts_nested_attributes_for。

谢谢!

最佳答案

最后,我找到了两个解决方案:

  • 在团队模型中添加回调以手动触发回调功能
  • 使用 attribute_will_change!覆盖 setter 方法:
    class User
    belongs_to :team
    has_many :addresses
    accepts_nested_attributes_for :addresses
    attr_accessor :dummy

    def dummy=(value)
    attribute_will_change!("dummy") if @dummy != value
    @dummy = value
    end

    ...
    end
  • 关于ruby-on-rails-4 - Rails4 : How to trigger the callback for attr_accessor while using accepts_nested_attributes_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29073686/

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