6

我有 2 个模型:

视频:

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

d

缩略图:

class Thumbnail < ActiveRecord::Base

  belongs_to :video

end

我正在使用 YouTubeG gem 来搜索视频。

搜索返回的每个视频在视图中都有一个表单:

<% 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 -%>

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

这似乎是错误的,因为我想保存此视频的所有缩略图。

当我尝试保存时,我得到

视频控制器中的 ActiveRecord::AssociationTypeMismatch#create

参数:

{"commit"=>"保存", "video"=>{"name"=>"Karajan - 贝多芬第七交响曲", "url"=>"s8eigkwmMEo", "user_id"=>"1", " thumbnails"=>{"url"=>" http://i.ytimg.com/vi/s8eigkwmMEo/0.jpg "}}} <应该有4个缩略图

4

2 回答 2

6

我找到了正确答案:

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

代替

<%  f.fields_for :thumbnails, video do |t| %>
于 2009-08-22T12:02:09.963 回答
0

您应该使用fields_for助手的索引功能:

  <% 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 -%>

透过铁轨看复杂形式的 edipode 三部曲: 第 1 集

于 2009-08-22T10:45:40.087 回答