I have a nested form in which I would like the form fields to only appear once for uploading a new image, then display the existing images, without any sort of CRUD capability. In essence, on the edit page, just give the option to add images, but not delete or update.
The relationship is a video has many video_images, which use paperclip for has_attached_file :image I’m trying the following in my controller now:
# GET /videos/new
# GET /videos/new.json
def new
@video = current_user.videos.build
@newthumbnail = @video.video_images.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @video }
end
end
And this in my view:
<%= f.fields_for @newthumbnail do |u| %>
<%= u.label :image, "Upload New Thumbnail" %> <br />
<%= u.file_field :image, :class => "image_uploader" %>
<% end %>
<p>
Or select a previous thumbnail
</p>
<div id="previous_thumbnails">
<!-- These will ultimately be dynamically generated as the existing image associations -->
<div class="previous_thumbnail" rel="1">
<img src="http://placehold.it/120x90" />
</div>
<div class="selected previous_thumbnail" rel="2">
<img src="http://placehold.it/120x90" />
</div>
<div class="previous_thumbnail" rel="3">
<img src="http://placehold.it/120x90" />
</div>
<div class="previous_thumbnail" rel="4">
<img src="http://placehold.it/120x90" />
</div>
</div>
But I end up with the following error:
unknown attribute: video_image
Which tells me that somewhere, there’s a mistranslation of singularity vs plurality. I can see why Rails would singularize it, as it is, in fact, a single entry. However, even overriding the name of the file field, and making name="video[video_image][image]" into name="video[video_images][image]", I get an error like so:
VideoImage(#39741260) expected, got Array(#9591480)
With params sent:
"video_images"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x000000054f1078 @original_filename="Bill OneManBand.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"video[video_images][image]\"; filename=\"Bill OneManBand.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/tmp/RackMultipart20120205-3582-1xp2duq>>},
So where am I going wrong? I feel like I may be taking the wrong approach to this…
Change this
to this
That should let the fields know that they’re part of the
videoand not just randomvideo_imagefieldsAlso make sure you have
accepts_nested_attributes_forin yourvideomodel.