How can I get FOUND_ROW () s from the active recording object in rails?

When querying a database with:

@robots = Robot.all(:condition => [:a => 'b'], :limit => 50, :offset => 0) 

What is the best way to get the total number of rows without :limit ?

In raw MySQL, you can do something like this:

 SELECT SQL_CALC_FOUND_ROWS * FROM robots WHERE a=b LIMIT 0, 50 SELECT FOUND_ROWS(); 

Is there an active recording method?

+4
source share
6 answers

Robot.count is actually the solution you want.

Looking at one of the comments above, it looks like you may have a misunderstanding of how .count works. It returns the number of all rows in the table only if there are no parameters.

but if you go into the same conditions that you go to all / find, for example:

 Robot.count(:conditions => {:a => 'b'}) 

.count () will return the number of lines matching the specified conditions. To be obvious - you can even save the hash condition as a variable, to go both ways - reduce duplication, therefore:

 conds = {:a => 'b'} @robots = Robot.all(:conditions => conds, :limit => 50) @num_robots = Robot.count(:conditions => conds) 

This means that you cannot make an account after the fact in the result set (as in your example). those. you cannot just run your query and then ask how many rows would be found. You really need to call .count specifically.

+2
source

This works for me:

 ps = Post.all(:limit => 10, :select => "SQL_CALC_FOUND_ROWS *") Post.connection.execute("select found_rows()").fetch_hash => {"found_rows()"=>"2447"} 

This probably won't work for joins or anything complicated, but it works for a simple case.

+3
source
 search = Robot.all(:condition => ["a=b"], :offset => 0) @robots = search[0..49] @count = search.count 

This should get what you want, get all the robots to count, and then set @robots to the first 50. Maybe a little more expensive on the front of the resources if the robot table is huge.

Of course you can:

 @count=Robot.all(:condition => ["a=b"], :offset => 0).count @robots=Robot.all(:condition => ["a=b"], :limit => 50, :offset => 0) 

but this will delete the database twice for each request (although the rails have query caching).

Both solutions use only active recording, and therefore are independent of the database.

Why do you need the amount returned by the request? if its pagination looks like Will_paginate (Railscast) , which can be extended using AJAX, etc.

+1
source

Try find_by_sql , which may help.

0
source

Is @robots.size what you are looking for? Or Robot.count ?

Otherwise, please specify.

0
source

I think hakunin is right.

You cannot get a row return for a query by simply resizing the resulting array of the query.

 @robots = Robot.find_by_sql("Your sql") or @robots = Robot.find(:all , :conditions=>["your condiitons"] ) @robots.size or @robots.count 
0
source

Source: https://habr.com/ru/post/1313132/


All Articles