Rails query optimization, doing it the wrong way?

Viewed 24

I've got a Team and a Tag model, linked through a simple TeamTag model with foreign keys (tag_id, team_id). I'm trying to get all the tags from specific teams with a specific tag_type, with one query. Here's what I'm at right now :

TeamTag.joins(:tag, :team).where(tags: {tag_type: 1}, teams: {id: [1,2]}).map(&:tag)

Is there a way to start with Tag.joins... instead so I can avoid the .map() at the end that does an extra query ?

When I'm trying the other way I get a join error :

Tag.joins(:teams, :team_tags).where(tag_type:0, teams: {id: u.teams})
Traceback (most recent call last):
ActiveRecord::ConfigurationError (Can't join 'Tag' to association named 'teams'; perhaps you misspelled it?)

Thanks !

1 Answers

The reason you get "Can't join 'Tag' to association named 'teams'" is because tag isn't directly related to teams, but it has another table in between (team_tags).

joins allows you to refer to such relationships as:

Tag.joins(team_tags: :team)

Comma-separated values mean they're directly related to the table/model you're invoking joins in.

You could start from Tag, but using the relationship between tag -> team_tags -> team:

Tag.joins(team_tags: :team).where(teams: { tag_type: 1, id: [1, 2] })
Related