tomekfranek
tomekfranek

Reputation: 7099

How to write scope with belongs_to object?

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?

Upvotes: 9

Views: 13589

Answers (2)

lucas
lucas

Reputation: 1151

Here's an alternative syntax for the where clause:

class Job
  scope :accepted_with_active_company, ->() {
    joins(:company).where(companies: { state: 'accepted' }) 
  }
end

Upvotes: 0

shadysayed
shadysayed

Reputation: 226

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

Upvotes: 20

Related Questions