我有两个模型:
模型 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
但没有成功..我做错了什么?