Null property selection using named scopes/lambda in Ruby on Rails
I have an object JobBreakdown
that has_one :invoice
. If a JobBreakdown has an invoice (i.e. invoice_id is not nil) 开发者_运维知识库then it is considered INVOICED. If not, it is consider UNINVOICED. Users want to be able to select from a drop down box Invoiced or Uninvoiced and have correct records show up.
How would I write a named scope to test and return the right records? Something along the lines of
named_scope :is_invoiced, lambda {|is_invoiced| {:conditions => :invoice.nil? == is_invoiced}}
NB: I am using ruby 1.8.7, rails 2.3.5
I'm not sure, this is the right syntax for rails 2.x but at least it'll give you an idea of how to do that.
named_scope :is_invoiced, lambda { |is_invoiced| :condition => is_invoiced ? "invoice IS NOT NULL" : "invoice IS NULL" }
or maybe even something like this:
named_scope :is_invoiced, lambda { |is_invoiced| :condition => "invoice IS #{is_invoiced ? 'NOT' : ''} NULL" }
精彩评论