How to write scope with belongs_to object?

11,699

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
Share:
11,699
tomekfranek
Author by

tomekfranek

Updated on July 23, 2022

Comments

  • tomekfranek
    tomekfranek almost 2 years

    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?

  • tomekfranek
    tomekfranek over 11 years
    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/active‌​record-3.2.8/lib/act‌​ive_record/associati‌​ons/join_dependency.‌​rb:112:in `build'
  • shadysayed
    shadysayed over 11 years
    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