Rails “find_all_by” vs “.where”

*爱你&永不变心* 提交于 2019-12-17 16:04:21

问题


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.


回答1:


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



回答2:


I think the main advantage is being able to add additional criteria to where, find_all_by is limited to the field of the dynamic selector. If you only have one condition you are searching by then I think it is a wash, but when you start adding 3 or 4, dynamic finders can be ugly. Hashes are nice to look at, and you could pass a hash of conditions as a parameter if needed. Dynamic finders are cool, but I think where scales in a cleaner way and is more readable.



来源:https://stackoverflow.com/questions/11232971/rails-find-all-by-vs-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!