Can't Save Image Attributes with Paperclip in Rails 4

自古美人都是妖i 提交于 2019-12-05 13:11:36
carols10cents

I was able to get a setup similar to yours working with the following changes:

In ProductsController#create, instead of building the image separately, let the nested attributes handle it and just do:

@product = Product.new(product_params)

And allow the nested parameters (I figured out the image_attributes: [:image] from this question):

def product_params
  params.require(:product).permit(:name, :part_number, images_attributes: [:image])
end

This is what my parameters look like in the logs for a create request:

{
   "utf8"=>"✓", 
   "authenticity_token"=>"7EsPTNXu127itgp4fbohu672/L4XnSwLEkrqUGec3pY=", 
   "product"=>{
     "name"=>"whatever", 
     "part_number"=>"12345", 
     "images_attributes"=>{
       "0"=>{
         "image"=>#<ActionDispatch::Http::UploadedFile:0x007feb0c183b08 
           @tempfile=#<Tempfile:/var/folders/6k/16k80dds0ddd6mhvs5zryh3r0000gn/T/RackMultipart20131031-51205-emaijs>, 
           @original_filename="some-image.png", 
           @content_type="image/png", 
           @headers="Content-Disposition: form-data; name=\"product[images_attributes][0][image]\"; filename=\"ponysay.png\"\r\nContent-Type: image/png\r\n">
        }
      }
    }, 
    "commit"=>"Create"}

And I see an insert into products and an insert into images.

If that doesn't work, could you post your ProductsController#new and your new product form?

EDIT AFTER YOUR EDIT:

I have 3 different things in my app/views/products/new.html.erb and ProductsController#new that might be affecting your results:

  1. In the form_for, I have multipart: true as in the paperclip documentation:

    <%= form_for @product, :url => products_path, :html => { :multipart => true } do |f| %>
    
  2. Because Product has_many :images, in my form I have fields_for :images instead of fields_for :image:

    <%= f.fields_for :images do |i| %>
      <%= i.file_field :image %>
    <% end %>
    
  3. This fields_for doesn't show anything on the page unless in the ProductsController#new I build an image; does your Product.new do this by any chance?

    def new
      @product = Product.new
      @product.images.build
    end
    

Are there any particular reasons for these differences you have? Does your code work if you change it to match mine?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!