Ruby on rails 使用has_many:through在RubyonRails中建模人与人之间的关系
我想模拟一个人与另一个人的关系,这种关系不一定是等级关系(即朋友和同事,而不是父母和孩子),我感兴趣的是捕捉关于每种关系的更多细节(例如注释、关系类型、建立日期)。最后,我想使用act_as_树关系来导航/绘制这些关系 迁移:Ruby on rails 使用has_many:through在RubyonRails中建模人与人之间的关系,ruby-on-rails,associations,self-join,Ruby On Rails,Associations,Self Join,我想模拟一个人与另一个人的关系,这种关系不一定是等级关系(即朋友和同事,而不是父母和孩子),我感兴趣的是捕捉关于每种关系的更多细节(例如注释、关系类型、建立日期)。最后,我想使用act_as_树关系来导航/绘制这些关系 迁移: class CreateProfiles < ActiveRecord::Migration def self.up create_table :profiles do |table| table.column :firstName, :st
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 CreateProfilesfalse do |表|
table.column my_id:integer
table.column\u id:integer
table.column relationshipType:字符串
表1.1列日期已建立:日期
表1.2列注释:文本
表1.2时间戳结束结束定义自关闭
drop_表:关系结束
模型:
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
class-Person“我的id”
有很多:人:通过=>:关系
结束
类关系
问题:
has\u和\u属于\u many
关联时才会出现。对于常规的有很多:通过关联,联接表的模型与任何其他ActiveRecord模型一样,需要一个ID列
您的\u person\u id
,它将作为关系访问。您的\u person
,并明确说明您正在处理一个person
实例?另一个选项可以是关系。您可以
acts\u as\u tree:foreign\u key=>“我的\u id”
正如我在回答问题时提到的,看起来你最大的困难将是双向关系。一旦人a连接到人B,并不意味着人B连接到人a。不幸的是,据我所知,在ActiveRecord中很难做到这一点。处理互惠关系的最简单方法可能是同时创建两个方向。它使数据库的大小增加了一倍,但至少列表是可用的。