how can I do inverse of self-reference with rails

Viewed 8

I have the user model like :

  has_many :users, class_name: 'User'
  belongs_to :master_user, class_name: 'User', optional: true, inverse_of: :users

I Would like to find :

User.first.master_user it's ok

MasterUser.users but get an error : "NameError: uninitialized constant MasterUser"

1 Answers

You are getting that error because you have not defined a MasterUser model. I am guessing you only have a User model as described in your question. If you want to find the users belonging to a "master_user" then you need to find a "master_user" first, then request its users. It would look something like this:

user_with_a_master = User.where.not(master_user_id: nil).first
master             = user_with_a_master.master_user
master_users       = master.users
Related