问题
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?
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
Edit
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
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.
回答1:
This is the best I could get:
def days_attributes=(*attrs)
self.days = []
super(*attrs)
end
Hopefully is not too late.
回答2:
Add a reject_if
option like the following:
accepts_nested_attributes_for :days, reject_if: :all_blank
This should prevent the behaviour you described.
来源:https://stackoverflow.com/questions/28591636/rails-4-has-many-nested-attributes-to-replace-all