Skip to content

Instantly share code, notes, and snippets.

@anoldguy
Created December 10, 2012 16:19
Show Gist options
  • Save anoldguy/4251598 to your computer and use it in GitHub Desktop.
Save anoldguy/4251598 to your computer and use it in GitHub Desktop.
Transform to AR or AR + Squeel?

Can this be transformed into AR/Squeel?

  select students.shirt as size, count(students.shirt) as quantity
    from students, memberships, teams
    where students.shirt is not NULL
    and  students.id = memberships.student_id
    and memberships.team_id = teams.id
    and teams.id = #{team.id}
    group by students.shirt
  • Teams has many students through memberships
  • Students has many teams through memberships
  • Memberships belong to teams, students
@anoldguy
Copy link
Author

Whoops, let me try this differently.

Season

class Season < ActiveRecord::Base
  has_many :teams, :dependent => :destroy
end

Team

class Team < ActiveRecord::Base
  has_many :memberships, :dependent => :destroy
  has_many :students, :through => :memberships
  belongs_to :season
end

Membership

class Membership < ActiveRecord::Base
  belongs_to :team
  belongs_to :student
end

Student

class Student < ActiveRecord::Base
  has_many :memberships
  has_many :teams, :through => :memberships
end

All I have is a season object. So I'm iterating over the season.teams collection and passing the team.id into this query. That's why I'm joining on the teams table. Also, the report is run once for each team, so that's where the results get displayed under.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment