Rails“find_all_by"vs “.where" [英] Rails "find_all_by" vs ".where"

查看:37
本文介绍了Rails“find_all_by"vs “.where"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

这样做会有什么好处吗?现在似乎 .wherefind_all_by 更常见.

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

推荐答案

我认为使用 .where 是更好的方法.

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

当您使用基于属性的查找器时,您将不得不通过缺少调用的方法并最终定义一个类方法,通过 class_eval,返回您的结果.这是您可能不需要执行的额外处理.

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.

此外,串连起来:find_by_this_and_this_and_this_and_this... 可能会变得丑陋.

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

在这里查看 rails 如何实现基于属性的查找器

github 上的模块 DynamicMatchers 中缺少方法:

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

这篇关于Rails“find_all_by"vs “.where"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆