Named_scope multiple conditions

Hi everyone,

I have a working named_scope here, however it’s too cluttered.
Anyone got a better (more efficient) and concise alternative?

Thanks.

============================================
named_scope :filter, lambda { |*args|
if
args.first && args.second == nil
{} # return all records

       if args.first.blank?
           { :conditions => ["status = ?", args.second] }

       if
         args.second.blank?
           { :conditions => ["invoice_number= ?", args.first] }

     else
       { :conditions => ["nvoice_number= ? and status = ?",

args.first, args.second] }
end
end
end
}

On Jul 16, 11:42 am, Jermaine [email protected] wrote:

Hi everyone,

I have a working named_scope here, however it’s too cluttered.
Anyone got a better (more efficient) and concise alternative?

Thanks.

well named_scope :filter, lambda {|*args|
{:conditions => {:status => args.first, :invoice_number =>
args.second}.reject{|k,v| v.blank?}}
}

is more compact and i think does the same thing as your code. With
anything like this any time you save when building up the conditions
will be dwarfed by the time it takes to run the actual query

Fred

Hi Fred,

Thanks for the suggestion. However what did you mean specifically with
your last comment?

With anything like this any time you save when building up the conditions
will be dwarfed by the time it takes to run the actual query

aaah I-C.
Okay thanks for clearing that up! great stuff

You might want to split those two into named_scopes of their own
though - for more modularity and possible scope chaining opportunities
elsewhere in the code.
Handling whether one of those arguments, which I presume are user
entered, is blank can be handled in the controller.

Thanks for the suggestion. However what did you mean specifically with
your last comment?

With anything like this any time you save when building up the
conditions

will be dwarfed by the time it takes to run the actual query

Putting words in Frederick’s mouth, but it simply means that it’s
ridiculously quick to build up the conditions object in Ruby compared to
actually executing the SQL on the database (and communicating the SQL
and
response over the socket).

Cheers,

Andy