Rails 3, mongoid, carrierwave, nested object form
I'm using carrierwave to upload photos to a World model. I can't seem to get the upload form right:
class World
include Mongoid::Document
embeds_many :photos
accepts_nested_attributes_for :photos
end
class Photo
include Mongoid::Document
mount_uploader :image, WorldPhotoUploader
embedded_in :world
end
# show.haml
= form_for world, :html => {:multipart => true} do |f|
= f.fields_for world.photos.build do |photo|
= photo.file_field :image
This gives me this form input:
<input id="world_photo_image" name="world[photo][image]" type="file">
Which doesn't work, I get
Cannot serialize an object of class ActionDispatch::Http::UploadedFile into BSON.
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"e2PzZlSY0NwiCqDWn7ZMNwqnypP+GC23PcMuy+uGyF0=",
"world"=>{"photo"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x00000103182ac8 @original_filename="Black Box fish.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"world[photo][image]\"; filename=\"Black Box fish.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/IY/IY7PGAf2F9OD6CIKr1RQo++++TI/-Tmp-/RackMultipart20110917-57084-z开发者_开发技巧woyfy>>}},
"commit"=>"Upload",
"id"=>"pluto"}
The input that seems to work is:
<input id="world_photo_image" name="world[photos][][image]" type="file">
But i'm not sure how to create the form to get that
I have this (with your names):
<%= form_for @world, :multipart => true do |f| %>
<%= f.fields_for 'photos[0]' do |attachments| %>
<%= attachments.file_field :image %>
<% end %>
<% end %>
This gives the desired format. You can increase the index with javascript if you don't know beforehand how many images are going to be uploaded.
Then you may simply have in you controller:
@world = World.new(params[:world])
But don't forget this line in your model:
embeds_many :photos, cascade_callbacks: true
as per this issue.
Also, it is redundant to have accepts_nested_attributes_for
for an embedded document as this is the default.
10.times {@world.photos.build}
in your World controller and you will get 10 input fields with correct names, thanks goes to Radar @ irc.freenode.net #RubyOnRails
精彩评论