Ricky Mason
Ricky Mason

Reputation: 1828

Joining 2 tables using a join table

I set up a relationship between the following three tables: User, Armies and User_Armies

UserArmies is my join table, which contains user_id and army_id

I want to build the following query using active record, but can't figure out how:

SELECT ua.number_owned, a.population 
FROM user_armies ua 
INNER JOIN armies a 
ON ua.army_id = a.id 
WHERE ua.user_id = 1;

User has_many User_Armies. And Armies has_may User_Armies (just a normal set up using a join table).

Does anyone know the correct active record syntax to do this query!?

Thanks!

Upvotes: 0

Views: 78

Answers (2)

knotito
knotito

Reputation: 1392

UserArmies.joins(:armies, :user).where('users.id = 1').map { |e| { e.number_owned => e.armies.map(&:population) } } 

Something like that should work...

Upvotes: 1

Eugene Tkachenko
Eugene Tkachenko

Reputation: 232

User_Armies model:

belongs_to :user
belongs_to :armies

User model:

has_many :user_armies
has_many :armies, through: :user_armies

Armies model:

has_many :user_armies
has_many :users, through: :user_armies

Controller:

@user = User.find(params[:id])
@users = @user.armies

Upvotes: 1

Related Questions