如何解决此质量分配错误?铁轨上的红宝石

时间:2013-03-10 18:44:06

标签: ruby-on-rails ruby ruby-on-rails-3.2 mass-assignment

我试图让用户能够在两个“Tag”对象之间创建“链接”关系。

标签

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

new.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 = Tag.new | link = Link.new | link.from_tag = a | link.to_tag = b | link.value = 5 | link.save

1 个答案:

答案 0 :(得分:0)

在您的链接模型中尝试添加:
attr_accessible:from_tags_attributes,:to_tags_attributes