How to define one-to-many connection between a same model through another model
- by Mekajiki
I want to define one-to-many relationship as follows;
User has one introducer
User has many newcomers(who is introduced by the user)
Use "Introduction" model instead of adding a column to users table.
My table and model definition is as follows;
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"
User model:
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
Introduction model:
class Introduction < ActiveRecord::Base
belongs_to :introducer, class_name: 'User'
belongs_to :newcomer, class_name: 'User'
end
This works fine:
user1.newcomers.push user2
but,
user2.introducer
# => nil
How can I define belongs_to relationship correctly?