开发者

Lambda condition for linked object in Ruby on Rails

开发者 https://www.devze.com 2023-03-10 17:03 出处:网络
I am trying to write a named scope in a class for Invoice.Invoice objects have a link to a Job object. Job objects have a link to a Company object.

I am trying to write a named scope in a class for Invoice. Invoice objects have a link to a Job object. Job objects have a link to a Company object.

class Invoice < ActiveRecord::Base
belongs_to :job

class Job < ActiveRecord::Base
belongs_to :company

I want the scope to be base on whether the ID of the Company related to the Job matches the passed in value.

I am attempting it as something like this

named_scope :job_company, lambda{|job_company_id| {:co开发者_JAVA技巧nditions => {job.company.id => job_company_id}}}

This is giving me an error that says

undefined local variable or method `job' for #Class:0x103239160

How do I write the lambda function for this?

NB: I am using Ruby 1.8.7 with Rails 2.3.5


A named_scope is basically just a class method, so inside the lambda, the scope of self is Invoice. There is no job instance or local variable, hence the error.

But, this should work:

named_scope :job_company, lambda{|job_company_id| { :joins => { :job => :company }, :conditions => ["jobs.company_id = ?", job_company_id] }}
0

精彩评论

暂无评论...
验证码 换一张
取 消