Search code examples
ruby-on-railsactiverecordarel

Rails 3 joining a related model with it's default scope


I'm trying to query across models with the following setup

Class Scorecard < AR::Base
  default_scope where(:archived => false)
  belongs_to :user
  has_many :scorecard_metrics
end

Class ScorecardMetric < AR::Base
  belongs_to :scorecard
end

Class User < AR::Base
  has_many :scorecards
end

I am trying to query from scorecard metrics with a named scope that joins scorecard and I want it to include the default scope for scorecard, my current implementation (which works) looks like this

# on ScorecardMetric
scope :for_user, lambda { 
  |user| joins(:scorecard).
         where("scorecards.user_id = ? and scorecards.archived = ?", user.id, false) 
}

This just seems messy to me, is there any way to join and include the default scope of the joined association?


Solution

  • Looks like I found the answer I was looking for, I just did this

    scope :for_user, lambda { |user| joins(:scorecard).where('scorecards.user_id = ?', user.id) & Scorecard.scoped }
    

    which is much nicer without the duplicated logic