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
Author by
tomekfranek
Updated on July 23, 2022Comments
-
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 acceptedCompany
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 over 11 yearsI 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'
-
shadysayed over 11 yearsThe 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 isbelongs_to
what you should do is have joins(:company) instead of joins(:companies). I have edited the answer to reflect that