Bowen
Bowen

Reputation: 105

Is there a way to defer an ActiveRecord query (like QuerySet in Django)?

I want to be able to build a query in sections without evaluating the final statement until a later time in Ruby on Rails.

Specifically this behavior (copied from Djano docs):

a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset.

Upvotes: 0

Views: 533

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

This is how it works by default unless you access the results. That is, you can put this into your controller:

@widgets = Widget.enabled
@widgets = @widgets.where(foo: 'bar')
# ... more conditions here if you want ...

And then in your view put this:

<%- @widgets.each do |w| %>
  ...
<% end %>

The DB query won't run until that @widgets.each line.

You can test this by using logger.info statements in your control to see where the query is actually being executed.

Upvotes: 2

Related Questions