we just figured out how polymorphic relations are working in Rails 4 but we face a little problem as the relations always creates a new entry instead of updating the existing relation.
Why updating a polymorphic relation creates a new entry instead of updating the existing one?
f.e. with a picture class...
The Picture Model
class Picture < ActiveRecord::Base
belongs_to :picable, polymorphic: true
end
The Shop Model
class Shop < ActiveRecord::Base
has_one :picture, :as => :picable
accepts_nested_attributes_for :picture
end
The Form
<%= 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 %>
The Controller
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
add :id to the :picture_attributes section of your params method in the controller. That will almost definitely work. Another method would be to add to your accepts_nested_attributes_for:
accepts_nested_attributes_for :picture, :update_only => true