Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Saving many new objects in a nested form

I have 2 models:

Video:

class Video < ActiveRecord::Base
  belongs_to :user
  has_many :thumbnails
  attr_accessor :search, :saveable
  accepts_nested_attributes_for :thumbnails, :allow_destroy => true
en

d

Thumbnail:

class Thumbnail < ActiveRecord::Base

  belongs_to :video

end

I am using the YouTubeG gem in order to search for videos.

Each video that is returned by the search has a form in the view:

<% form_for :video, :url => videos_path, :html => { :class => :form } do |f| -%>
  <%= f.hidden_field :url, :value => video.unique_id %>
  <%= f.hidden_field :name, :value => video.title %>
  <%= f.hidden_field :user_id, :value => current_user.id %>
  <% if video.thumbnails.present? %>
    <%  f.fields_for :thumbnails, video do |t| %>
      <% video.thumbnails.each do |thumbnail| -%>
        <%=image_tag thumbnail.url %>
        <%=t.text_field :url, :value => thumbnail.url %>
      <% end -%>
    <% end -%>
  <% end %>
  <%= f.submit "Save" %>
<% end -%>

The f.fields_for :thumbnails produces <input type="hidden" value="http://i.ytimg.com/vi/s8eigkwmMEo/0.jpg" name="video[thumbnails][url]" id="video_thumbnails_url"/>

which seems to wrong because I want to save all thumbnails for this video.

When I try to save I get

ActiveRecord::AssociationTypeMismatch in VideosController#create

Parameters:

{"commit"=>"Save", "video"=>{"name"=>"Karajan - Beethoven Symphony No. 7", "url"=>"s8eigkwmMEo", "user_id"=>"1", "thumbnails"=>{"url"=>"http://i.ytimg.com/vi/s8eigkwmMEo/0.jpg"}}} < there should be 4 thumbnails

like image 802
Kieran Hayes Avatar asked Aug 22 '09 10:08

Kieran Hayes


1 Answers

I found the correct answer:

<% f.fields_for "thumbnails_attributes[]", Thumbnail.new do |t| %>

instead of

<%  f.fields_for :thumbnails, video do |t| %>
like image 198
Kieran Hayes Avatar answered Oct 14 '22 00:10

Kieran Hayes