Rails 4 has_many nested_attributes替换所有 [英] Rails 4 has_many nested_attributes to replace all
问题描述
我想使用nested_attributes用新对象替换所有我的旧关联对象.最好的方法是怎么做到的?
I want to use nested_attributes to replace all my old associated objects by the new ones. How is the best way to do that?
如果我使用下面的代码,则每次我使用nested_attributes更新主对象时,都会创建关联的新对象.
If I use the code below, every time I update my main object with nested_attributes, new objects associated are created.
accepts_nested_attributes_for :days
修改
我在下面的before_validation
回调中找到了它:
I´ve got it with the before_validation
callback below:
def replace_days
db_days = days.where('id IS NOT NULL')
all_days = days
all_days -= db_days
self.days = all_days
end
问题在于我对子模型的唯一验证. Rails将进入数据库以验证唯一性.由于验证时我的替换品不在数据库中,因此出现验证错误.不知道如何绕过此方法,这是否是最好的方法.我希望Rails具有一些本机函数或参数,可以帮助我完全按照自己的意愿进行操作.
The problem with that is my unique validation on the child model. Rails is going to the database to validate uniqueness. Since my replacement is not on database at the validation moment, got validation error. Don´t know how to bypass this and if this is the best way to do that. I hope that rails have some native function or parameter that helps me to do exactly what I want.
推荐答案
这是我能得到的最好的结果:
This is the best I could get:
def days_attributes=(*attrs)
self.days = []
super(*attrs)
end
希望还不算太晚.
这篇关于Rails 4 has_many nested_attributes替换所有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!