Aarmora
Aarmora

Reputation: 1153

Using ActiveRecord to find a many to many association

I'm still pretty inexperienced with Rails' activerecord and I'm struggling to find a good way to match up multiple records that are associated with multiple other records.

I'm running a league with multiple seasons and teams. I want to find all teams that are in the currently active seasons. So...multiple seasons and multiple teams.

The models:

class Season < ActiveRecord::Base
    has_many :team_seasons, :dependent => :delete_all
    has_many :teams, :through => :team_seasons
end

class Team < ActiveRecord::Base
  has_many :team_seasons, :dependent => :delete_all
  has_many :seasons, :through => :team_seasons
end

I am thinking it should be something like @teams = Team.includes(:seasons).where(:active => true) but the sql this returns is SELECTteams.* FROMteamsWHEREteams.active= 1 which is just checking whether the team is active and not checking the seasons at all. Plus that query takes a LONG time to run.

So...is there a good way to do this? I know I could just make a manual sql statement but I really would like to be able to use and learn the activerecord way to do this.

Thanks in advance!

Upvotes: 0

Views: 28

Answers (1)

Aarmora
Aarmora

Reputation: 1153

This @teams = Team.includes(:seasons).where("seasons.active = true") did the trick.

Upvotes: 1

Related Questions