Tôi có hai mô hình, liên kết và thẻ, được liên kết thông qua một phần ba, link_tags. Mã sau nằm trong mô hình Liên kết của tôi.accepts_nested_attributes_for với has_many =>: thông qua Tùy chọn
Hội:
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 Actions:
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
Xem mã từ new.html.erb:
<% form_for [current_user, @link], :url => account_links_path do |f| %>
<%= render :partial => "form", :locals => { :f => f } %>
<% end %>
Và một phần tương ứng:
<%= 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>
Các dòng mã sau đây, trong tạo hành động trong bộ điều khiển liên kết ném một lỗi:
@link = @current_user.links.build(params[:link])
Lỗi: Tag(#-621698598) expected, got Array(#-609734898)
Có bước bổ sung cần thiết trong has_many =>: thông qua trường hợp? Đây dường như là những thay đổi được chỉ định duy nhất cho trường hợp has_many cơ bản.
Tôi không thể để tái tạo vấn đề của bạn dựa trên mã bạn đã đăng. Bạn có thể đăng các phần kết hợp (các dòng has_many/attribute_to/etc) của ba mô hình của bạn, cả các hành động điều khiển có liên quan (liên kết # mới, liên kết # tạo) và bất kỳ mã xem nào có liên quan đến biểu mẫu liên kết. – EmFi
Tôi đã thêm mã cho các liên kết, hành động của bộ điều khiển và chế độ xem. Cảm ơn bạn đã giúp đỡ. –