Will Paginate: Limit number of results - ruby-on-rails

Im using the will paginate gem for ruby. I am using will paginate to get a bunch of people and sorting on a field. What I want is only the first 100 of those. Essentially the top people. I cant seeem to do this. How would i go about it? Thanks

As far as my knowledge goes will_paginate doesn't provide an option for this, I just had a root around in its source too to check, but if you don't mind having a subquery in your conditions it can be done...
people = Person.paginate(page: 10).where('people.id IN (SELECT id FROM people ORDER BY a_field LIMIT 100)').per_page(5)
people.total_pages
=> 20
Replace a_field with the field your sorting on, and this should work for you.
(note, the above uses the current version of will_paginate (3.0.2) for its syntax, but the same concept applies to older version as well using the options hash)

will_paginate gem will take total_entries parameter to limit the number of entries to paginate.
#problems = Problem.paginate(page: params[:page], per_page: 10,
total_entries: 30)
This gives you 3 pages of 10 records each.

people = Person.limit(100).paginate(:per_page => 5)

Related

Order by score using Pagy pagination?

I am currently trying to order some ActiveRecord records by score. In my controller i have:
def index
#pagy, #drivers = pagy(
Driver.select(
'drivers.*',
'(drivers.no_races + drivers.no_poles + drivers.no_podiums + drivers.no_wins) AS score'
).reorder('drivers.score DESC'),
page: params[:page],
items: 16
)
end
I am using Pagy for the pagination. As the code shows, I do a query to select all drivers and then add together 3 columns in the table as 'score'. I then want to order by score going from high to low and show 16 records per page.
When the page loads it seems to order by driver id. I can't see anywhere else that i have an order by, but i did add reorder to override anything else.
Anyway for whatever reason i'm stuck with the wrong ordering. Any direction is appreciated :-)
Mockup - http://29qg.hatchboxapp.com/drivers
Ok so it was a simple error in the end. "score" is ambiguous because i was using score as an alias and i also had a column in the table called score.

How to search data on created at less than in thinking sphinx

Using thinking_sphinx to fetch data from records. It working fine but facing an issue that not find any to get records on date comparison like created_at greater than or less than. I check their official documentation also Thinking Sphinx
Is thinking sphinx provide that way? If yes then can we do that
It is possible, but it's not entirely obvious.
What you'll need to do is add an extra column in the SELECT clause, and then filter by that. Something along the lines of:
Model.search "pancakes",
:select => "*, IF(created_at > #{1.year.ago.to_i}, 1, 0) AS time_match",
:with => {:time_match => 1}
You will need to have created_at as an attribute in your index file for this to work.

Rails find all order, found 0 results expected 2

I'm having trouble sorting my table based on the votes column, votes is a multivalued attribute so I use count and try to sort it based on that. here is the code
#topics = Topic.find(:all,:order=>'#topic.votes.count DESC')
Rails returns an error that says
ActiveRecord::RecordNotFound in TopicsController#index
Couldn't find all Topics with 'id': (all, {:order=>"#topic.votes.count DESC"}) (found 0 results, but was looking for 2)
Just starting out with rails and still confused with some things, your help will be much appreciated.
this is Rails 2 syntax being used in higher Rails version.
You can do something like this:
Topic.joins(:votes).group('topics.id').order('count(topics.id) DESC')
Instead of join include is best and faster option
Topic.include(:votes).group('topics.id').order('count(topics.id) DESC')
Thanks to ahmed and snehal, I was able to find out the answer I'm looking for, which is
Topic.left_outer_joins(:votes).group('topics.id').order('count(topics.id) DESC')

Limit the maximum number of results in ActiveRecord + Kaminari

When using Rails and Kaminari, is it possible to limit the maximum number of results to be returned for a given query?
#things = Thing.page(params[:page]).per(10)
Assuming we have 500k+ Thing records in the database, how can I ensure that Kaminari's paginate method will never return more than 10,000 rows to paginate?
Kaminari has a max_per_page option that may be helpful, but it may work via the limit scope method also offered here.
So, I figured out a way to do that using an initializer for Kaminari in config/initializers/kaminari_config.rb:
Kaminari.configure do |config|
config.default_per_page = 10
config.max_per_page = 100
config.max_pages = 100
end
In the above case, 100 * 100 = 10,000 maximum total results
More info here
max_per_page actually sets settings globally. To have individual resource based settings, Kaminari supports Array type objects as well. So, something like below works perfect:
limited_newsfeeds = Newsfeed.order(:created_at).limit(20)
#newfeeds = Kaminari.paginate_array(limited_newsfeed).page(params[:page]).per(3)
You may easily use this #newsfeed object same like normal collection in kaminari views, like
<%= paginate #newsfeeds, remote: true %>
TIP: Using limit() method directly before/after page() doesn't serve the purpose. It either overwrites kaminari's limit (when used after page() method), or gets replaced-by kaminari's limit (when used before page() method)
Source: https://github.com/kaminari/kaminari#paginating-a-generic-array-object
So you're interested in just the top 10k rows? This should do it, but I would consider adding some sorting criteria in there (before the call to limit) so that your chosen 10000 rows make sense.
Thing.limit(10000).page(params[:page]).per(10)

Rails Mongoid model query result returns wrong size/length/count info even when using limit

When querying on a certain model in my rails application, it returns the correct results, excerpt the size, length or count information, even using the limit criteria.
recipes = Recipe
.where(:bitly_url => /some.url/)
.order_by(:date => :asc)
.skip(10)
.limit(100)
recipes.size # => 57179
recipes.count # => 57179
recipes.length # => 57179
I can't understand why this is happening, it keeps showing the total count of the recipes collection, and the correct value should be 100 since I used limit.
count = 0
recipes.each do |recipe|
count += 1
end
# WAT
count # => 100
Can somebody help me?
Thanks!
--
Rails version: 3.2.3
Mongoid version: 2.4.10
MongoDB version: 1.8.4
From the fine manual:
- (Integer) length
Also known as: size
Get's the number of documents matching the query selector.
But .limit doesn't really alter the query selector as it doesn't change what the query matches, .offset and .limit alter what segment of the matches are returned. This doesn't match the behavior of ActiveRecord and the documentation isn't exactly explicit about this subtle point. However, Mongoid's behaviour does match what the MongoDB shell does:
> db.things.find().limit(2).count()
23
My things collection contains 23 documents and you can see that the count ignores the limit.
If you want to know how many results are returned then you could to_a it first:
recipes.to_a.length
As mentioned in one of the comments, in newer Mongoid versions (not sure which ones), you can simply use recipes.count(true) and this will include the limit, without needing to query the result set, as per the API here.
In the current version of mongoid (5.x), count(true) no longer works. Instead, count now accepts an options hash. Among them there's :limit option
criteria.count(limit: 10)
Or, to reuse whatever limit is already set on the criteria
criteria.count(criteria.options.slice(:limit))

Resources