Find rails with block

I saw the Rails find method accepting a block as

 Consumer.find do |c| c.id == 3 end 

Which is similar to Consumer.find (3).

What are some of the use cases where we can actually use a block to find ?

+6
source share
2 answers

This is a shortcut for .to_a.find { ... } . The source code method is used here:

 def find(*args) if block_given? to_a.find(*args) { |*block_args| yield(*block_args) } else find_with_ids(*args) end end 

If you pass a block, it calls .to_a (loads all records) and calls Enumerable#find in the array.

In other words, it allows you to use Enumerable#find on ActiveRecord::Relation . This can be useful if your condition cannot be expressed or evaluated in SQL, for example. request for serialized attributes :

 Consumer.find { |c| c.preferences[:foo] == :bar } 

To avoid confusion, I would prefer a more explicit version:

 Consumer.all.to_a.find { |c| c.preferences[:foo] == :bar } 
+12
source

The result may be similar, but the SQL query is not like Consumer.find(3)

It extracts all consumers and then filters them based on the block. I can’t think of a use case where it might be useful

Here is an example request in the console

  consumer = Consumer.find {|c|c.id == 2} # Consumer Load (0.3ms) SELECT `consumers`.* FROM `consumers` # => #<Consumer id: 2, name: "xyz", ..> 
+4
source

Source: https://habr.com/ru/post/978496/


All Articles