我试图让用户能够在两个“标签”对象之间创建“链接”关系。
标签
class Tag < ActiveRecord::Base
attr_accessible :ref, :location_info
belongs_to :user
has_many :to_links, :foreign_key => 'from_id', :class_name => 'Link'
has_many :to_tags, :through => :to_links
has_many :from_links, :foreign_key => 'to_id', :class_name => 'Link'
has_many :from_tags, :through => :from_links
end
关联
class Link < ActiveRecord::Base
attr_accessible :from_id, :to_id, :value
belongs_to :from_tag, :foreign_key => "from_id", :class_name => "Tag"
belongs_to :to_tag, :foreign_key => "to_id", :class_name => "Tag"
end
链接控制器
class LinksController < ApplicationController
def new
@user = current_user
@tags = @user.tags
@link = Link.new
end
def create
end
新的.html.erb
<%= form_for(@link) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :from_tag %>
<%= f.collection_select :from_tag, @tags, :id , :ref %>
<%= f.label :to_tag %>
<%= f.collection_select :to_tag, @tags, :id , :ref %>
<%= f.label :value %>
<%= f.text_field :value %>
<%= f.submit "Create", class: "btn btn-large btn-primary" %>
<% end %>
我知道通常在 create 方法中,您会将 params[:link] 传递给 new ,它会在单击 create 后从表单中接收这些,但因为我无法批量分配 from_tag 和 to_tag 我不知道如何创建这个链接对象就像你在控制台中一样,没有像这样的批量分配
a = Tag.new | b = 新标签 | 链接 = Link.new | 链接.from_tag = a | 链接.to_tag = b | 链接值 = 5 | 链接.保存