Rails“find_all_by”vs“.where”
我有以下代码:
def maturities InfoItem.find_all_by_work_order(self.work_order).map(&:maturity) end
我正考虑将其更改为:
def maturities InfoItem.where(work_order: self.work_order).map(&:maturity) end
这有什么好处吗? 看起来像。现在比find_all_by
更常见。
我的观点是使用.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
我认为主要的优点是能够在其中添加额外的标准,find_all_by仅限于动态选择器的字段。 如果你只有一个条件你正在搜索那么我认为这是一个洗,但当你开始添加3或4时,动态查找器可能是丑陋的。 散列很好看,如果需要,您可以将条件的散列作为参数传递。 动态查找器很酷,但我认为在哪里以更清洁的方式进行扩展并且更具可读性。