Will
Will

Reputation: 5590

Active record create query in multiple steps

I'm a bit confused by active record, it just seems to fire the query at any time you stop, ie.

@model.where( :store_id => @sid )

Which is fine, but what if I want to build a query like this:

query = @model.where( :store_id => @sid )

if(some_condition)
  query.offset(50)

and then execute the query (not actually what I'm doing but a very simple example). Is there a way to put together the query in steps and then tell it to execute?

Upvotes: 1

Views: 430

Answers (2)

alf
alf

Reputation: 18550

Actually, ActiveRecord will do exactly what you want. It's called lazy loading. You might be getting confused by the rails console, which calls .inspect behinds the scenes on the result of the line.

Check out this question: Lazy loading in Rails 3.2.6

Upvotes: 3

Shane
Shane

Reputation: 514

This already works like you want it too.

where() returns an instance of ActiveRecord::Relation.

The relation won't execute it's database call until it needs to. The reason you might be experiencing otherwise is that you're testing it in the console, which prints the output of each statement (thus loading the relation). You can test whether a relation has been loaded via the loaded() method.

Try this on the console:

m = @model.where(:store_id => @sid); # the semicolon will silence the output

m.loaded?  # nil
m          # executes db call, will print out the contents of the relation
m.loaded?  # true

Upvotes: 2

Related Questions