Rails 4 has_many nested_attributes to replace all

筅森魡賤 提交于 2019-12-10 21:46:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!