How to define one-to-many connection between a same model through another model

Posted by Mekajiki on Stack Overflow See other posts from Stack Overflow or by Mekajiki
Published on 2014-08-22T15:54:11Z Indexed on 2014/08/22 16:21 UTC
Read the original article Hit count: 338

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord