Rails HABTM 与视图(formtastic)
我有两个模型:
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,我选择了模型 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
但没有成功..我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
协会还需要知道使用什么外键。尝试更新到这个。我还没有尝试过,所以请告诉我它是否有效。
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.