-1

我有两个模型:

模型 NetworkObject 尝试描述“主机”。我想要一个包含源和目标的规则,所以我尝试使用同一个类中的两个对象,因为创建两个不同的类没有意义。

class NetworkObject < ActiveRecord::Base
  attr_accessible :ip, :netmask, :name
  has_many :statements
  has_many :rules, :through =>:statements
end

class Rule < ActiveRecord::Base
  attr_accessible :active, :destination_ids, :source_ids
  has_many :statements
  has_many :sources, :through=> :statements, :source=> :network_object
  has_many :destinations, :through => :statements, :source=>  :network_object
end

为了构建 HABTM,我确实选择了 Model JOIN。所以在这种情况下,我创建了一个名为 Statement 的模型:

class Statement < ActiveRecord::Base
  attr_accessible :source_id, :rule_id, :destination_id
  belongs_to  :network_object, :foreign_key => :source_id
  belongs_to :network_object,  :foreign_key => :destination_id
  belongs_to :rule
end

问题是:使用不同的foreign_keys将两个belongs_to添加到同一个类是否正确?我尝试了所有组合,例如:

belongs_to :sources, :class_name => :network_object, :foreign_key => :source_id

但没有成功..我做错了什么?

4

1 回答 1

1

关联还需要知道要使用什么外键。尝试将其更新为此。我还没有尝试过,所以让我知道它是否有效。

class Rule < ActiveRecord::Base
  attr_accessible :active, :destination_ids, :source_ids
  has_many :statements
  has_many :sources, :through => :statements, :class_name => "NetworkObject", :foreign_key => "source_id"
  has_many :destinations, :through => :statements, :class_name => "NetworkObject", :foreign_key => "destination_id"
end
于 2010-03-30T03:10:11.930 回答