Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails "find_all_by" vs ".where"

I have the following code:

def maturities   InfoItem.find_all_by_work_order(self.work_order).map(&:maturity) end 

I was thinking about changing it to:

def maturities   InfoItem.where(work_order: self.work_order).map(&:maturity) end 

Would there be any advantage to this? It seems like .where is more common than find_all_by nowadays.

like image 991
ardavis Avatar asked Jun 27 '12 18:06

ardavis


1 Answers

My opinion is that using .where is a better approach.

When you use attribute based finders, you are going to have to tunnel through a method missing call and eventually define a class method, via class_eval, that returns your result. This is extra processing that you may not need to do.

Also, stringing together: find_by_this_and_this_and_this_and_this... can get ugly.

See how rails accomplishes attribute based finders here

Method missing from module DynamicMatchers on github:

def method_missing(name, *arguments, &block)   match = Method.match(self, name)    if match && match.valid?     match.define     send(name, *arguments, &block)   else     super   end end 
like image 148
Kyle Avatar answered Sep 21 '22 13:09

Kyle