1

我正在尝试为我的 ruby​​ on rails 应用程序建模一个有向图我有两个模型,标签和连接

class Connection < ActiveRecord::Base
  attr_accessible :cost, :from_id, :to_id
  belongs_to :from_tag, :foreign_key => "from_id", :class_name => "Tag" 
  belongs_to :to_tag, :foreign_key => "to_id",   :class_name => "Tag" 
  end



class Tag < ActiveRecord::Base
  attr_accessible :location_info, :reference
  has_many :to_connections, :foreign_key => 'from_id', :class_name => 'Connection' 
  has_many :to_tags, :through => :to_connections  
  has_many :from_connections, :foreign_key => 'to_id', :class_name => 'Connection' 
  has_many :from_tags, :through => :from_connections
  end

当我像这样创建标签时

a = Tag.create(:reference => "a", :location_info => "Tag A")
b = Tag.create(:reference => "b", :location_info => "Tag B")

它工作正常。

但是当我试图在两者之间建立联系时

Connection.create(:from_tag => a, :to_tag => b, :cost => 5)

我收到一条错误消息

“ActiveModel::MassAssignmentSecurity::Error:无法批量分配受保护的属性:from_tag 和 to_tag”

,谁能看到问题?

4

1 回答 1

2

您不能批量分配关系。

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

connection = Connection.new
connection.from_tag = a
connection.to_tag = b
connection.cost = 5
connection.save
于 2013-03-04T12:16:45.800 回答