如何在使用accepts_nested_attributes_for时,正确触发Rails4中attr_accessor的回调方法?

更新于
2026-10-09 19:21:35
2阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计204个文字,预计阅读时间需要1分钟。

如何在使用accepts_nested_attributes_for时,正确触发Rails4中attr_accessor的回调方法?

请检查伪代码如下:

rubyclass Team has_many :users accepts_nested_attributes_for :users, allow_destroy: trueend

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

请检查伪代码:

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.

谢谢!

如何在使用accepts_nested_attributes_for时,正确触发Rails4中attr_accessor的回调方法?

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

>在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

本文共计204个文字,预计阅读时间需要1分钟。

如何在使用accepts_nested_attributes_for时,正确触发Rails4中attr_accessor的回调方法?

请检查伪代码如下:

rubyclass Team has_many :users accepts_nested_attributes_for :users, allow_destroy: trueend

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

请检查伪代码:

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.

谢谢!

如何在使用accepts_nested_attributes_for时,正确触发Rails4中attr_accessor的回调方法?

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

>在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