Deeply nested Rails forms using belong_to not working?

我与影子孤独终老i 提交于 2019-12-03 15:50:39
Tyler Rick

Here's another possible solution that I posted in a similar question: https://stackoverflow.com/a/12064875/47185

Something like this...

  accepts_nested_attributes_for :company
  def company_attributes=(attributes)
    if attributes['id'].present?
      self.company = Company.find(attributes['id'])
    end
    super
  end

I ran into the same problem, it just seems that rails doesn't support using nested models like this: you can't save a new object with a nested model that exists, e.g imagine this situation:

class Monkey < ActiveRecord::Base
end
class Banana < ActiveRecord::Base
    belongs_to :monkey
    accepts_nested_attributes_for :monkey
end

This wont work if you try on the console:

banana = Banana.create!
monkey = Monkey.new
monkey.attributes = {:banana_attributes => { :id => banana.id}}

But its simple to work around this, in your form you don't need to set any nested attributes if your banana is already persistent, you just need to have a hidden field on the monkey form with banana_id, which will result in something like:

monkey.attributes = {:banana_id => banana.id}

And that will save just fine.

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