开发者

rails HABTM versus view (formtastic)

开发者 https://www.devze.com 2022-12-24 20:37 出处:网络
I have two models: The model NetworkObject try to describe \"hosts\". I want to have a rule with source and destination, so i\'m trying to use both objects from the same class since it dont makes sen

I have two models:

The model NetworkObject try to describe "hosts". I want to have a rule with source and destination, so i'm trying to use both objects from the same class since it dont makes sense to create two different classes.

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

To build the HABTM i did choose the开发者_运维百科 Model JOIN. so in this case i created a model named Statement with:

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

The problem is: is right to add two belongs_to to the same class using different foreign_keys? I tried all combinations like:

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

but no success.. anything that i am doing wrong?


The associations also need to know what foreign key to use. Try updating it to this. I have not tried this so let me know if it works or not.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号