9

I have the following models

Models

Job
  belongs_to :company
Company
  has_many :jobs

Right now I select all the Jobs which have an accepted Company using the following method:

def self.with_accepted_company
  Job.all.reject {|job| job.company.state != "accepted" }
end

But I would like to use scope for that and use it with other scopes. Is this possible to write that scope in the Job model?

strivedi183
  • 4,749
  • 2
  • 31
  • 38
tomekfranek
  • 6,852
  • 8
  • 45
  • 80

2 Answers2

20

I would do something like this (from http://guides.rubyonrails.org/active_record_querying.html)

class Job
  scope :accepted_with_active_company, ->() {
    joins(:company).where('companies.state' => "accepted") 
  }
end
shadysayed
  • 236
  • 2
  • 5
  • I get an error using this scope ```>> Job.accepted_with_active_company.inspect ActiveRecord::ConfigurationError: Association named 'companies' was not found; perhaps you misspelled it? from /Users/rege/.rvm/gems/ruby-1.9.3-p194@ckdatabase/gems/activerecord-3.2.8/lib/active_record/associations/join_dependency.rb:112:in `build' ``` – tomekfranek Dec 16 '12 at 11:38
  • 3
    The error message tells you that you don't have an association named :companies. The original code assumes it was a `has_many` relation but in face it is `belongs_to` what you should do is have joins(:company) instead of joins(:companies). I have edited the answer to reflect that – shadysayed Dec 16 '12 at 16:08
0

Here's an alternative syntax for the where clause:

class Job
  scope :accepted_with_active_company, ->() {
    joins(:company).where(companies: { state: 'accepted' }) 
  }
end
lucas
  • 1,050
  • 12
  • 21