使用 has_many :through 在 Ruby-on-Rails 中建模人与人的关系
-
25-09-2019 - |
题
我想对一个人与另一个人的关系进行建模,这种关系不一定是分层的(即朋友和同事,而不是父母和孩子),我有兴趣捕捉有关每种关系的更多细节(例如备注、关系类型、建立日期)。最后,我想使用 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
问题:
- 如何正确定义这些表之间的关系?
- 由于 my_id/your_id 组合是唯一的,因此消除关系表上的 :id 是否有意义?
- 'my_id' 和 'your_id' 字段是否有更好的名称来利用 RoR 的约定?
- 如果其中一列的名称不是“parent_id”,我在处理 act_as_tree 关系时是否会遇到困难?
解决方案
前几天,也有人问过类似的问题: “Rails 中同一模型的多对多关系?”. 。我尝试广泛记录如何在那里进行循环关联。也许这会对你有所帮助?
Rails 中没有 ID 的表只能用
has_and_belongs_to_many
协会。与常规的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'
正如我在回答中提到的 其他问题, ,看起来你最大的困难将是双向关系。一旦人 A 与人 B 有联系,并不意味着人 B 与人 A 有联系。不幸的是,据我所知,这在 ActiveRecord 中很难实现。
不隶属于 StackOverflow