Stefan Schuchlenz
Stefan Schuchlenz

Reputation: 117

Rails: has_many and belongs_to with same model

I have a resource named Team which belongs to a user (in client_id) and should have many users (in users) in a Rails 3 application.

How can I specify

belongs_to :user

and

has_many :users

in one model?

Upvotes: 0

Views: 776

Answers (2)

Anand
Anand

Reputation: 3760

 # in models/team.rb
class Team
  belongs_to :client, class_name: 'User' # @team.client
  has_many :users # @team.users
end

Upvotes: 1

Blake Simpson
Blake Simpson

Reputation: 1088

Have you tried has_and_belongs_to_many ?

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Many-to-many

EDIT:

It may work like this:

belongs_to :user # User is the owner
has_many :members, class_name: "User", foreign_key: "user_id"

Upvotes: 1

Related Questions