gpt4 book ai didi

ruby-on-rails - rails : Saving many new objects in a nested form

转载 作者:行者123 更新时间:2023-12-03 16:09:02 25 4
gpt4 key购买 nike

我有 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 来搜索视频。

搜索返回的每个视频在 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 -%>

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 in VideosController#create

参数:

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

最佳答案

我找到了正确答案:

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

代替

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

关于ruby-on-rails - rails : Saving many new objects in a nested form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1315706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com