Rails"find_all_by"vs".where"

ard*_*vis 26 ruby-on-rails where dynamic-finders

我有以下代码:

def maturities
  InfoItem.find_all_by_work_order(self.work_order).map(&:maturity)
end
Run Code Online (Sandbox Code Playgroud)

我正考虑将其更改为:

def maturities
  InfoItem.where(work_order: self.work_order).map(&:maturity)
end
Run Code Online (Sandbox Code Playgroud)

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

Kyl*_*yle 25

我的意见是使用.where是一种更好的方法.

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

另外,串起来:find_by_this_and_this_and_this_and_this ......可能会变得难看.

了解rails如何在此处完成基于属性的查找程序

github上的模块DynamicMatchers缺少方法:

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
Run Code Online (Sandbox Code Playgroud)

  • 在Rails 4中将不推荐使用`find_all_by_*`方法.最好在这里使用`where`. (8认同)