views:

547

answers:

2

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

A: 

You should use index feature of the fields_for helper:

  <% video.thumbnails.each do |thumbnail| -%>
  <%  f.fields_for "thumbnail[]", thumbnail do |t| %>  
    <%=image_tag thumbnail.url %>
      <%=t.text_field :url, :value => thumbnail.url %>
    <% end -%>
  <% end -%>

Look through rails casts edipode trilogy about complex forms: Episode 1

Bogdan Gusiev
A: 

I found the correct answer:

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

instead of

<%  f.fields_for :thumbnails, video do |t| %>
Kieran Hayes