Search code examples
ruby-on-railsruby-on-rails-4activerecordhas-many-throughhas-many

Scope ActiveRecord Relation based on record data


I a model like this:

class Club < ActiveRecord::Base
  belongs_to :organization
  has_many :career_clubs
  has_many :careers, through: :career_clubs
end

Which appropriately gets careers through the table career_clubs. So far this is only using the club's id field and getting all the records in the career_clubs table with that id.

What I actually want this to do, is use both the id and organization_id, so that it gets all the career_clubs with matching id and organization_id.

I know how to scope things using static data like below, but that doesn't seem to work here.

has_many :career_clubs, -> { where active: true }

Solution

  • This should do what you want

    has_many :career_clubs, ->(club) { 
      where(club_id: club.id, organization_id: club.organization_id)
    }