gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes_for with has_many => :through Options

转载 作者:行者123 更新时间:2023-12-03 10:29:23 25 4
gpt4 key购买 nike

我有两个模型,链接和标签,通过第三个,link_tags 关联。以下代码在我的 Link 模型中。

协会:

class Link < ActiveRecord::Base
has_many :tags, :through => :link_tags
has_many :link_tags

accepts_nested_attributes_for :tags, :allow_destroy => :false,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end

class Tag < ActiveRecord::Base
has_many :links, :through => :link_tags
has_many :link_tags
end

class LinkTag < ActiveRecord::Base
belongs_to :link
belongs_to :tag
end

links_controller 操作:
  def new
@link = @current_user.links.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @link }
end
end

def create
@link = @current_user.links.build(params[:link])

respond_to do |format|
if @link.save
flash[:notice] = 'Link was successfully created.'
format.html { redirect_to links_path }
format.xml { render :xml => @link, :status => :created, :location => @link }
else
format.html { render :action => "new" }
format.xml { render :xml => @link.errors, :status => :unprocessable_entity }
end
end
end

从 new.html.erb 查看代码:
<% form_for [current_user, @link], :url => account_links_path do |f| %>
<%= render :partial => "form", :locals => { :f => f } %>
<% end %>

以及相应的部分:
  <%= f.error_messages %>

<p>
<%= f.label :uri %><br />
<%= f.text_field :uri %>
</p>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>

<h2>Tags</h2>
<% f.fields_for :tags_attributes do |tag_form| %>
<p>
<%= tag_form.label :name, 'Tag:' %>
<%= tag_form.text_field :name %>
</p>
<% unless tag_form.object.nil? || tag_form.object.new_record? %>
<p>
<%= tag_form.label :_delete, 'Remove:' %>
<%= tag_form.check_box :_delete %>
</p>
<% end %>
<% end %>

<p>
<%= f.submit 'Update' %>
</p>

下面这行代码,在 Link Controller 的 create Action 中抛出了一个错误:
@link = @current_user.links.build(params[:link])

错误: Tag(#-621698598) expected, got Array(#-609734898)
在 has_many => :through 案例中是否需要额外的步骤?这些似乎是基本 has_many 情况的唯一指示更改。

最佳答案

看看你的代码行

<% f.fields_for :tags_attributes do |tag_form| %>

您只需要使用 :tags而不是 :tags_attributes .
这将解决您的问题

确保您在 Controller 中构建了链接和标签,例如
def new
@link = @current_user.links.build
@link.tags.build
end

关于ruby-on-rails - accepts_nested_attributes_for with has_many => :through Options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2212622/

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