gpt4 book ai didi

ruby-on-rails - rails "find_all_by"与 ".where"

转载 作者:行者123 更新时间:2023-12-03 10:28:05 26 4
gpt4 key购买 nike

我有以下代码:

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

这样做会有什么好处吗?好像是 .wherefind_all_by 更常见如今。

最佳答案

我的观点是使用 .where是一种更好的方法。

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

此外,串在一起:find_by_this_and_this_and_this_and_this... 会变得丑陋。

See how rails accomplishes attribute based finders here

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

关于ruby-on-rails - rails "find_all_by"与 ".where",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11232971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com