简体   繁体   中英

Polymorphic association and nested attributes

I have a Product model and an Image model (based on paperclip).

class Product < ActiveRecord::Base
  has_many :images, as: :imageable,
                    dependent: :destroy
  accepts_nested_attributes_for :images
end

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  has_attached_file :picture
end

I want to add image for my products in the same page I create product ( /products/new ). Here is the form :

<%= form_for(@product, html: { multipart: true}) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div>
    <%= f.label :name, t('product.name') %>
    <%= f.text_field :name %>
  </div>                    
  <div class="file_field">
     <%= f.fields_for :image do |images_form| %>
       <%= images_form.file_field :image %>
     <% end %>
  </div>
  <%= f.submit @submit_button %>
<% end %>

Then I go to the /products/new page, I fill in the fields, and click on the submit button. The server try to renders the product's show page, but it doesn't work because the image has not been saved. I have the following error :

undefined method `picture' for nil:NilClass

for the following line in the product's show page

image_tag(@product.images.first.picture.url(:medium))

I wonder why the image has not be saved and I see that the server renders the following message :

Unpermitted parameters: images_attributes

So I added image attributes in the permit products params ( like there ) :

def product_params
  params.require(:product).permit(:name, :sharable, :givable, image_attributes: [:name, :picture_file_name, :picture_content_type, :picture_file_size])
end

But it doesn't change anything, I always have the same error message. Do you have an idea where does the permission issue come from ?

You may need to change

params.require(:product).permit(:name, :sharable, :givable, image_attributes: [:name, :picture_file_name, :picture_content_type, :picture_file_size])

to

params.require(:product).permit(:name, :sharable, :givable, images_attributes: [:name, :picture])

You define a has_many association, so in your view, it should be f.fields_for :images

<%= f.fields_for :images do |images_form| %>
    <div class="file_field">         
       <%= images_form.file_field :picture %>         
    </div>
<% end %>

In your controller, you should build some images first and add your images_attributes to permitted parameters.

@product = Product.new
3.times {@product.images.build}

your view will show 3 file fields.

Any chance this has to do with your file_field being

<%= images_form.file_field :image %>

instead of the following?

<%= images_form.file_field :picture %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM