使用has_many:through在Ruby-on-Rails中建立人与人之间的关系

时间:2010-02-03 14:12:07

标签: ruby-on-rails associations self-join

我想模仿一个人与另一个人的关系,其中关系不一定是等级的(即朋友和同事,而不是父母和孩子),我有兴趣获取关于每个关系的更多细节(例如笔记,关系类型,确定日期)。最后,我想使用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

问题:

  1. 如何正确定义这些表之间的关系?
  2. 由于my_id / your_id组合是唯一的,因此消除关系表上的:id是否有意义?
  3. “my_id”和&amp;是否有更好的名称? 'your_id'字段是否可以使用RoR的约定?
  4. 如果其中一列不是名称'parent_id',我是否会遇到act_as_tree关系的问题?

1 个答案:

答案 0 :(得分:2)

  1. 就在几天前,有人问过类似的问题:“Many-to-many relationship with the same model in rails?”。我试图广泛记录如何在那里做循环协会。也许那会对你有帮助吗?

  2. 只有has_and_belongs_to_many关联才能看到Rails中没有ID的表。使用常规has_many :through关联,连接表的模型与任何其他ActiveRecord模型类似,并且需要ID列

  3. 我不知道这里有一个好的约定,但这些例子有点奇怪。你将以relationship.your的身份访问它们,这对我个人来说感觉有点尴尬。也许your_person_id,可以作为relationship.your_person访问,并明确表示您正在处理Person实例?另一个选项可能是relationship.you

  4. 我从未使用过acts_as_tree,但您可以使用如下参数调用它:acts_as_tree :foreign_key => 'my_id'

  5. 正如我在回答other question时提到的那样,看起来你最大的困难是双向关系。一旦一个人A与一个人B相连,就不会暗示B人与A人有关。不幸的是,从我所知道的,在ActiveRecord中很难完成。