Rails在ActiveRecord :: Relation Object中查找记录,而无需再次查询数据库

Nei*_*eil 14 ruby activerecord ruby-on-rails

我想在ActiveRecord::Relation对象中找到特定记录,以便我可以获取该记录的属性.

以下工作,但问题是它使用该find_by语句再次访问数据库.它不应该.rails应该有一种方法可以在对象中找到该ActiveRecord::Relation对象,而不必再次查询数据库.

#returns an ActiveRecord::Relation object
@blogs = Blog.all

# Search for the blog within that ActiveRecord::Relation object, NOT the database
@blogs.find_by(id: 1).title #do this statement but don't hit the database again
Run Code Online (Sandbox Code Playgroud)

Bro*_*tse 16

加载实现后,您可以使用常规数组方法.find这里实际上是非常有趣的方法 - 如果指定了块,它将被委托给关系目标:

@blogs.find {|b| b.id == 1}
Run Code Online (Sandbox Code Playgroud)


And*_*icz 12

当你打电话时find_by,它会打到数据库.

关系对象用于延迟加载db结果.

加载完all呼叫后,您可以在生成的阵列中进行搜索.

如果你想在ruby过程中查看已经存在于内存中的结果,那么你应该使用findor detect(它做同样的事情)在数组中查看.我倾向于使用detect,所以很明显它没有打到数据库:

@blogs.detect { |b| b.id == 1 }
Run Code Online (Sandbox Code Playgroud)

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-detect