我想模仿一个人与另一个人的关系,其中关系不一定是等级的(即朋友和同事,而不是父母和孩子),我有兴趣获取关于每个关系的更多细节(例如笔记,关系类型,确定日期)。最后,我想使用act_as_tree关系来导航/绘制这些关系。
迁移:
class CreateProfiles < ActiveRecord::Migration def self.up
create_table :profiles do |table|
table.column :firstName, :string
table.column :lastName, :string
table.column :telephone, :string
table.column :emailAddress, :string
table.column :location, :string
table.timestamps
end end def self.down
drop_table :profiles end end
class Relationship < ActiveRecord::Migration def self.up
create_table :relationships, :id => false do |table|
table.column my_id :integer
table.column your_id :integer
table.column relationshipType :string
table.column dateEstablished :date
table.column notes :text
table.timestamps end end def self.down
drop_table :relationships end end
模特:
class Person < ActiveRecord::Base
has_many :relationships, :foreign_key => "my_id"
has_many :persons :through => :relationships
end
class Relationship < ActiveRecord::Base
belongs_to :persons
acts_as_tree
end
问题:
答案 0 :(得分:2)
就在几天前,有人问过类似的问题:“Many-to-many relationship with the same model in rails?”。我试图广泛记录如何在那里做循环协会。也许那会对你有帮助吗?
只有has_and_belongs_to_many
关联才能看到Rails中没有ID的表。使用常规has_many :through
关联,连接表的模型与任何其他ActiveRecord模型类似,并且需要ID列
我不知道这里有一个好的约定,但这些例子有点奇怪。你将以relationship.your
的身份访问它们,这对我个人来说感觉有点尴尬。也许your_person_id
,可以作为relationship.your_person
访问,并明确表示您正在处理Person
实例?另一个选项可能是relationship.you
。
我从未使用过acts_as_tree,但您可以使用如下参数调用它:acts_as_tree :foreign_key => 'my_id'
正如我在回答other question时提到的那样,看起来你最大的困难是双向关系。一旦一个人A与一个人B相连,就不会暗示B人与A人有关。不幸的是,从我所知道的,在ActiveRecord中很难完成。