Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Does post query 'where' clause on ActiveRecordRelation hit the database?

activerecord performance

  • Please log in to reply
2 replies to this topic

#1 Giacomo

Giacomo

    Signalman

  • Members
  • 15 posts
  • LocationBologna

Posted 17 March 2014 - 04:18 PM

Hi all.

I'm executing a query like this:

my_data = MyModel.joins(:other_tables).where(...)
filtered_data = my_data.where('some other condition')

Does the filtered_data where clause hit again my database? 

 



#2 bugroll

bugroll

    Passenger

  • Members
  • 1 posts

Posted 17 March 2014 - 08:21 PM

Hi Giacomo,

 

Good question. Neither of those where calls will hit the database. The idea with ActiveRecord's query methods is that you can build up complex queries incrementally, much like you are above. It's only when you ask for the results (e.g. by calling filtered_data.each) that ActiveRecord will actually query the database. Does that make sense?



#3 Bharat Soni

Bharat Soni

    Dispatcher

  • Members
  • 55 posts
  • LocationAhmedabad

Posted 18 March 2014 - 05:49 AM

Hi Giacomo,

my_data = MyModel.joins(:other_tables).where(...)
filtered_data = my_data.where('some other condition')

The above code will hit the database twice.

 

In first query it query data according to the conditions.

 

And in second query it will run the query with conditions of first query and query conditions which you write for second.


Fun with Ruby on Rails






Also tagged with one or more of these keywords: activerecord, performance

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users