我们只是弄清楚Rails 4中多态关系是如何工作的,但我们面临一个小问题,因为关系总是创建一个新的条目,而不是更新现有的关系。
为什么更新多态关系会创建一个新条目而不是更新现有条目?
f.e。用图片类......
图片模型
class Picture < ActiveRecord::Base
belongs_to :picable, polymorphic: true
end
商店模式
class Shop < ActiveRecord::Base
has_one :picture, :as => :picable
accepts_nested_attributes_for :picture
end
表格
<%= f.fields_for :picture_attributes, @admin_shop.picture||Picture.new do |ff| %>
<div class="field">
<%= ff.label :url %><br />
<%= ff.text_field :url %>
</div>
<% end %>
控制器
def new
@admin_shop = Shop.new
end
# GET /admin/shops/1/edit
def edit
end
# POST /admin/shops
# POST /admin/shops.json
def create
@admin_shop = Shop.new(admin_shop_params)
respond_to do |format|
if @admin_shop.save
format.html { redirect_to admin_shops_url, notice: 'Shop was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
def update
respond_to do |format|
if @admin_shop.update(admin_shop_params)
format.html { redirect_to admin_shops_url, notice: 'Shop was successfully updated.' }
else
format.html { render action: 'edit' }
end
end
end
答案 0 :(得分:4)
将:id添加到控制器中params方法的:picture_attributes部分。这几乎肯定会奏效。另一种方法是添加到accepts_nested_attributes_for:
accepts_nested_attributes_for :picture, :update_only => true