accepts_nested_attributes_for to link to existing record, not create a new one

醉酒当歌 提交于 2019-11-28 07:35:56

Try to implement a :reject_if that check if the Store already exists and then use it:

class Product < AR::Base
  belongs_to :order
  has_and_belongs_to_many :stores

  accepts_nested_attributes_for :stores, :reject_if => :check_store

  protected

    def check_store(store_attr)
      if _store = Store.find(store_attr['id'])
        self.store = _store
        return true
      end
      return false
    end
end

I have this code working fine in a current project.

Please, let me know if you found a better solution.

I had the same problem and solved it by adding :id to the nested parameter list.

def family_params
  params.require(:family).permit(:user_id, :address, people_attributes: [:id, :relation, :first_name, :last_name)
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!