1
votes

Im having a problem transferring an SQLlite Rails 3 app over to a Mongoid Rails 3 app. In the SQLlite version, I am easily able to include an image upload form (using Paperclip) from one model ('image') within a nested form from another model ('product'). Here's my 'new' product form:

  <%= form_for @product, :html => {:multipart => true} do |f| %>
     <% f.fields_for :images do |image_form| %>
       <%= f.label :productphoto %>
       <%= f.file_field :productphoto %><br />
    <% end %>
 <% end %>

And here's the 'show' view:

    <% @product.images.each do |image| %>
      <%= image_tag image.productphoto.url(:gallerythumb) %><br />
    <% end %>

When I try to use the same product views in my Mongoid Rails 3 app (using Carrierwave), I get the following error:

    TypeError in Stores#show: 
    can't convert nil into String
    <%= image_tag product.image.url(:gallerythumb) %>

Im pretty sure my models in the Mongoid version are correct because if I add a string (like 'name') to my 'image' model and nest that in the 'Product' form, it works. Also, Im able to upload an image into a non-nested model form.

Any help would be greatly appreciated!

3

3 Answers

2
votes

I just had a similar problem myself. The problem is not the image upload I think, but the problem is that Rails doesn't recognize :images as being an Array. If you look into the Rails source of the fields_for helper you see that it checks for a method "_attributes=". If that's not there the form will be posted as normal fields and not as an array (params will be "images" instead of "images[0]")

You have to add the following line to your model:

accepts_nested_attributes_for :images
0
votes

This is most likely the issue that Lewy linked to -- that problem is specific to arrangements where your Carrierwave uploader is mounted on a child document in an embedded association and you are saving the parent, and though you don't explicitly show if this is how your data is modeled, I suspect that's the case since you noted that it works with a non-nested form (presumably saving the child document then, not the parent).

If you dig around in the discussions linked from that issue, you'll find some proposed workarounds. Here's what I ended up with to get Carrierwave working in this situation for me:

https://gist.github.com/759788

Full credit is to due to zerobearing2 whose gist I forked, I just made minor changes to get it working in Rails 3.0.3 and commented on my gist with summary info on the relevant discussions.