Rails 找到一个块 [英] Rails find with a block
问题描述
我已经看到 Rails find
方法将一个块作为
I have seen Rails find
method taking a block as
Consumer.find do |c|
c.id == 3
end
类似于 Consumer.find(3).
Which is similar to Consumer.find(3).
在哪些用例中我们可以实际使用块进行 find
?
What are some of the use cases where we can actually use block for a find
?
推荐答案
它是 .to_a.find { ... }
的快捷方式.这是该方法的源代码::>
It's a shortcut for .to_a.find { ... }
. Here's the method's source code:
def find(*args)
if block_given?
to_a.find(*args) { |*block_args| yield(*block_args) }
else
find_with_ids(*args)
end
end
如果您传递一个块,它会调用 .to_a
(加载所有记录)并调用 Enumerable#在数组上查找
.
If you pass a block, it calls .to_a
(loading all records) and invokes Enumerable#find
on the array.
换句话说,它允许您在 ActiveRecord::Relation
上使用 Enumerable#find
.如果您的条件无法在 SQL 中表达或评估,这会很有用,例如查询序列化属性:
In other words, it allows you to use Enumerable#find
on a ActiveRecord::Relation
. This can be useful if your condition can't be expressed or evaluated in SQL, e.g. querying serialized attributes:
Consumer.find { |c| c.preferences[:foo] == :bar }
为了避免混淆,我更喜欢更明确的版本:
To avoid confusion, I'd prefer the more explicit version, though:
Consumer.all.to_a.find { |c| c.preferences[:foo] == :bar }
这篇关于Rails 找到一个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!