当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails-4 – Rails4:如何在使用accepts_nested_attributes_for时触发attr_accessor的回调

来源:互联网 收集:自由互联 发布时间:2021-06-23
请检查伪代码: class Team has_many :users accepts_nested_attributes_for :users, allow_destroy: trueendclass User belongs_to :team has_many :addresses accepts_nested_attributes_for :addresses attr_accessor :dummy before_validation :ge
请检查伪代码:

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!”}}])(其他字段除了dummy属性外不会改变),它不会触发#generate_addresses_attributes回调它认为没有任何变化,没有保存,没有回调……

所以我的问题是如何触发虚拟属性的回调,或者强制save为accepts_nested_attributes_for.

谢谢!

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

>在Team模型中添加回调以手动触发回调功能
>使用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
网友评论