Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do has_many and has_one association in same model?

I need to do two associations in the same model. Where:

Team has_many User Now, I want that Team has_one Leader

This "Leader" will be a User

Im trying to use has_one throught but I think that association isn't work.

Leader.rb

class Leader < ActiveRecord::Base
belongs_to :user
belongs_to :team

Team.rb

class Team < ActiveRecord::Base
has_one :user, through: :leader
end

User.rb

class User < ActiveRecord::Base

belongs_to :team
has_one :captain

end

and the get following error around line 27:

NoMethodError in TeamsController#create

26 def create

**27 @team = current_user.teams.create(team_params)**

28 @team.save

29 respond_with(@team)

30 current_user.update(team_id: @team.id)
like image 647
Igor Martins Avatar asked Apr 10 '15 13:04

Igor Martins


4 Answers

In this case I think you need 2 model are enough

1). User model

class User < ActiveRecord::Base
   belongs_to :team
end

2). Team model

 class Team < ActiveRecord::Base
   has_many :users
   belongs_to :leader, class_name: 'User', foreign_key: :leader_id
 end
like image 98
Luan D Avatar answered Oct 16 '22 11:10

Luan D


How about setting a boolean flag in users table called leader. And then your association can become:

class Team < ActiveRecord::Base   
  has_many :users   
  has_one :leader, class_name: 'User', -> { where leader: true }
end
like image 27
usmanali Avatar answered Oct 16 '22 11:10

usmanali


Team has_many User Now, I want that Team has_one Leader

This "Leader" will be a User

Use inheritance (also called sub-classing), Leader is a User.

class User < ActiveRecord::Base
    belongs_to :team
end

class Leader < User
end

class Team < ActiveRecord::Base
    has_many :users
    has_one :leader
end

Your users table is also important. Ensure that users has t.belongs_to :team and t.string :type in its create_table method. Note that a Leader is a User and does not need a separate table, however you do need to allow ActiveRecord to record its type so it can return the correct Model later.

References:

inheritance specifically you need 'single table inheritance'

belongs_to scroll down for has_one and has_many, the three relationships used here.

like image 4
Matt Stevens Avatar answered Oct 16 '22 11:10

Matt Stevens


current_user.teams.create(team_params)

Teams is for a has_many association, you want current_user.create_team(team_params)

like image 1
j-dexx Avatar answered Oct 16 '22 09:10

j-dexx