Polymorphic assosiation and accepts_nested_attributes_for mass_assign issue Resolved

Nested Attributes Help Link
The issue was due to not placing lines correctly and in specific order in Product and Picture model. It was a long time ago when I was trying to handling nested attributes with polymorphic associated table and It was giving mass_assignment issue for values.

Posted this for those who don’t have much experience and will get benefit in same situation.

In Product  class:

has_many :pictures, :as => :imageable, :dependent => :destroy
accepts_nested_attributes_for :pictures, :allow_destroy => true
attr_accessible :pictures_attributes

In Picture class:

attr_accessible :image, :imageable_id, :imageable_type
mount_uploader :image, FileUploader # used for carrierwave gem
belongs_to :imageable, :polymorphic => true

In Product Controller: (new action)

@product = Product.new

In Product view: (_form.html.erb)

<%= form_for(@product, :html => {:multipart => true}) do |f| %>
<div class="field">
<%= f.fields_for :pictures do |pic|%>
<%= pic.label :image %><br/>
<%= pic.file_field :image%>
<div class="actions">
<%= f.submit %>
<% end %>

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: ,
Posted in Ruby Little Codes, Ruby on Rails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: