ruby-on-rails-4 – Rails4:如何在使用accepts_nested_attribut
发布时间:2020-12-17 01:34:43 所属栏目:百科 来源:网络整理
导读:请检查伪代码: 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 :generate_
请检查伪代码:
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模型中添加回调以手动触发回调功能 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |