Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to buffer an ActiveRecord query?

I'd like to save a query, then build on top of it, then execute it.

For example, somehow

query = Post.order('likes DESC') # buffer the query
query = query.limit(3) # add on top of it
query.run # run it - this is the wrong syntax fyi

Can this be done? What's the right syntax?

PS. I'm not sure if "buffer" is the right word, please correct me if I'm wrong.

Thanks!

like image 770
foobar Avatar asked Dec 06 '25 19:12

foobar


1 Answers

You don't need any "buffers" when building queries with ActiveRecord in Rails 3 because it uses Arel. Your query = Post.order('likes DESC') gives you instance of ActiveRecord::Relation. This object contains information about query, but not an actual data. To get data you can invoke .first or .all methods for example. It's way how rails framework (>= 3.0) implements so called "lazy initialization". It means that ActiveRecord::Relation is a kind of proxy. Real query to the database goes only when you're trying to get some fields of your model (or when you force load data with .all, .first, .last etc). Until this action you can build your chain of filtering conditions and be sure that you do not "disturb" database. Your code may be like this:

query = Post.order('likes DESC') # ActiveRecord::Relation object with info about your query
query = query.limit(3) # adds more filtering options
@posts = query.all # here ActiveRecord takes data from the database

#239 ActiveRecord::Relation Walkthrough will give you more understanding about ActiveRecord::Relation

like image 94
evilguc Avatar answered Dec 08 '25 11:12

evilguc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!