Ruby on Rails - Modelling a Directed Graph

余生长醉 提交于 2019-12-25 02:24:42

问题


I'm trying to model a directed graph for my ruby on rails application I have two Models, Tag and Connection

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

When I create a tag like so

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

It works fine.

But when I try to make a connection between the two

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

I get an error saying

"ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: from_tag and to_tag"

, can anyone see the problem?


回答1:


You cannot mass-assign relations.

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


来源:https://stackoverflow.com/questions/15201192/ruby-on-rails-modelling-a-directed-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!