Reputation: 587
My models have a many-to-many relationship where Coach could have coached many Teams, and a Team could have multiple coaches.(Assistant, Head, etc)
in Rails Console, when I run:
@coach = Coach.joins(:teams).select("coaches.first_name, coaches.last_name, teams.team_level")
returns:
=> [#<Coach first_name: "john", last_name: "doe">]
notice that it doesnt return the teams.team_level
, so I cant use @coach.team_level
on my view
When I do .to_sql
it returns:
=> "SELECT coaches.first_name, coaches.last_name, teams.team_level
FROM `coaches`
INNER JOIN `coach_teams` ON `coach_teams`.`coach_id` = `coaches`.`id`
INNER JOIN `teams` ON `teams`.`id` = `coach_teams`.`team_id`
Which is what I expect... So when I run this Query against my DB, I get the expected fields.
What am I doing wrong here/what am I not seeing? Thanks for looking into this!
Upvotes: 2
Views: 368
Reputation: 13925
It is actually good. You ask for a Coach model, you join the Team model with it.
So you actually just need @coach.teams.team_level
to access the team level.
The select can't change the schema of your modell, it can only filter down the attributes returned form the SQL, this way you need less roundtrip and less data transfer, but the structure is unchanged.
Upvotes: 1
Reputation: 12445
You're not doing anything wrong, you use a method of the Coach
model so you get Coach
model/s.
Since you're using a join on teams you can access the team_level
value without an additional query.
Upvotes: 1