我想按如下方式定义一对多关系;
我的表格和模型定义如下;
DB Scheme:
create_table "introductions", force: true do |t|
t.integer "introducer_id"
t.integer "newcomer_id"
t.datetime "created_at"
t.datetime "updated_at"
用户模型:
class User < ActiveRecord::Base
has_many :introductions, foreign_key: :introducer_id
has_many :newcomers, through: :introductions, source: :newcomer
belongs_to :introduction, foreign_key: :newcomer_id
belongs_to :introducer
end
简介模型:
class Introduction < ActiveRecord::Base
belongs_to :introducer, class_name: 'User'
belongs_to :newcomer, class_name: 'User'
end
这很好用:
user1.newcomers.push user2
但是,
user2.introducer
# => nil
如何正确定义belongs_to关系?
答案 0 :(得分:2)
首先,我认为应该使用has_one
代替belongs_to
。
然后,多亏了@Paven,我的解决方案就变成了,
User < ActiveRecord::Base
has_many :introductions, foreign_key: :introducer_id
has_many :newcomers, through: :introductions, source: :newcomer
has_one :introduction, foreign_key: :newcomer_id
has_one :introducer, through: :introduction, class_name: 'User'
end