Rails 3: How does “accepts_nested_attributes_for” work?

后端 未结 1 719
逝去的感伤
逝去的感伤 2020-12-13 02:52

Consider the following association:

class Product < ActiveRecord::Base
  belongs_to :shop
  accepts_nested_attributes_for :shop
end

If <

相关标签:
1条回答
  • 2020-12-13 03:27

    I think that you're trying to figure out creating a new associated item vs. associating with an existing item.

    For creating a new item, you seem to have it working. When you passed the id in shop_attributes, it did not work, because it's looking up an association that doesn't exist yet.

    If you're trying to associate with an existing item, you should be using the following:

    params[:product][:shop_id] = "20"
    

    This will assign the current product's shop to the shop with id 'shop_id'. (Product should have a 'shop_id' column.)

    0 讨论(0)
提交回复
热议问题