Ruby/Rails - Limit the size of a object/hash - ruby-on-rails

I have an object called #events containing about 50 records being pulled from a find condition of my model.
I'm currently displaying the results of the #object in my view like this....
<% for event in #events %>
<p><%= #event.name %></p>
<% end %>
Instead of displaying the entire 50 I would like shrink the set to about 10 records so it displays better on the page.
I cannot use :limit in the find condition since the object is being composed from a variety of loops where after each iteration it adds a few specific records.
So the issue is I have this object #events with 50 records, how can I change the object after its been composed so only the first 10 records remain?

First of all, if you'd like to have pagination, I strongly suggest taking a look at will_paginate
Alternatively, you can do the following to read the first 10 records only.
<% #events.first(10).each do |event| %>
<p><%= event.name %></p>
<% end %>
Or the last 10 records
<% #events.last(10).each do |event| %>
<p><%= event.name %></p>
<% end %>
I didn't test it but you get the point.

are you looking to completely do away with the other 40 or are you just wanting to pull off 10 per page for display purposes. if you are just doing this for display purposes i would look into the will_paginate gem. through its options you could set it so only 10 results per page are shown.

Take a look at will_paginate and kaminari. They both are designed to limit the records retrieved from the database, plus offer helpers for your views to provide the usual number of pages and current page lists.
Will_paginate has been around a while, and is pretty flexible. Kaminari is newer and looks like it has a cleaner interface.

Related

Boost query performance and showing records in Ruby on Rails

I have a table called Person with roughly a million records. I would like to display each of them as a card on the index page, but I am having performance issues. The view is rendered very slowly and is causing significant lag.
I simply had #persons = Person.all but it didn't work since it just crashed my app. Now, I am using the Person.find_in_batches method, which now allows me to display all the records within the page. Not only it takes a long time to load up the records but when I try to click a few buttons on the page, it either freezes or lags heavily. I'm lost on how I can improve performance.
For the record, here is my following code:
Person controller:
def index
batch_size = 5000
#people_in_batches = Person.find_in_batches(batch_size: batch_size)
end
Index view:
<% #people_in_batches.each do |batch|%>
<% batch.each do |person| %>
<div>
<span><%= person.name %></span>
<span><%= person.date_if_birth.strftime("%m/%d/%Y") %></span>
</div>
<% end %>
<% end %>
Thank you!
It doesn't matter how you query the million records, it still a million records.
What you should do is consider adding pagination on your page, so you would only needs to fetch records for the corresponding page. Just like Gmail.
So on the backend, you can use gem like https://github.com/kaminari/kaminari to help you with pagination.
Other than that, you should also consider adding filters on the page too, e.g. Active / Not Active, to reduce the number of records on page load.

Count the pictures per row in rails

Im made a gallery in rails by creating a div for each image-url in the database in my view. I would like to add a feature, that the user can specify the pictures per row and the number of rows per page on my edit-page. The value will be written to the database and the pagination should than be dynamic using the calculated value (pictures_per_row * rows_per_page).
Problem: Im using images.each method in my view to loop through the pictures and create a div for every image in the gallery. So they are created one after another. Concerning the results are paginated, gives me a specific number for pictures per page. But how do I accomplish something like:
for gallery.image.each do a div, but after 5 divs, continue in new line.
I think the pagination isnt the problem here, because it will paginate whatever the database query delivers.
Any ideas? Thanks in advance.
You could use each_slice. Something like:
<% #gallery.each_slice(5) do |slice| %>
<div class="row">
<% slice.each do |item| %>
<!-- Display images-->
<% end %>
</div>
<% end %>

Limit images show in post to last six

I have with me a set of posts created from a scaffold and images uploaded using paperclip gem. I would like to show on each users profile the last six images from the users last posts and for that I am filtering as such
<% #posts.limit(6).each do |tweet| %>
<% if post.media.present? %>
<%= link_to image_tag(post.media.url(:thumb)), tweet %><br>
<% end %>
<% end %>
In my controller I have the posts arranged as such
#posts = user.posts.order('created_at desc')
My question is. Why is it that when using the above code, NO image is displayed. On upping the count to 9, I get three images displayed, to 12 i get six images displayed and so on
First of all, you should not make the calls to the db/model (with limit) in the views. Call it directly in the controller :
#posts = user.posts.order(created_at: :desc).limit(6)
Then, I would do some debugging to be sure you have the records you want.
Use byebug for instance and call it just after you set you #posts instance variable to see what it contains. Do all the posts contain a media ?

Minimizing number of db-queries

Let's say we have a Post model.
In the beginning of a view I need to display the total number of posts, typically by
#posts.size
Later in the view I need to display all posts, typically by
#posts.each do |post|
end
This results in two queries.
If I had done the queries in the opposite order, it had resulted in one single query (presumably utilizing CACHE).
Is there any "trick" where I can achieve the (first) mentioned order with only one db query?
You can use for example #fragment-caching
<% cache 'posts_size' do %>
<%= #posts.size %>
<% end %>
Then when a Post is created you can expire the fragment
expire_fragment 'posts_size'

Cache only the main content in rails

Using Rails 3.1.1 and Heroku.
I believe this should be a fairly easy fix but I cannot find (and easily verify) how to do this. I have a very slow controller (6 sec) Product#show, with lots of N+1 and other things I will have to solve.
The website is a two-column website (main-column and right-column) where the main content from Product#show is shown in one column and daily product are shown in the other, including a "Random Product from the Database".
What I want to do is to let the content in main-column that is created by Product#show be cached (and thus bypass the controller and win 6 seconds). I do, however, want the right column to be dynamic (and loaded for each page request).
If I use caches_page :show it will cache the entire website, including the right-column, which makes me have to expire the cache every day in order to be able to load a new Daily Product. Not a good solution.
If I use cache('product-show' + #product.slug) do it only caches the view (right?) and still have to go through the controller.
So, how can I solve this?
You can achieve this with fragment caching like below:
def show
if !fragment_exist?("main_content")
#products = Product.all
#users_count = User.count
end
#random_products = Product.order("RANDOM()").limit(10)
end
show.html.erb
<!--MAIN CONTENT-->
<% cache("main_content") do %>
<%= #users_count %>
<% #products.each do |product| %>
<%= product.name %>
<% end %>
<% end %>
<!--SIDE CONTENT-->
<% #random_products.each do %>
<%= product.name %>
<% end %>
Use fragment caching, and don't load things in the controller.
If you have a very complex query, let it live in the controller as a scope, and only evaluate it in the view.
If you have a complex process to do so the query must be executed, use a helper method.
If you manage to just load lazy queries in the controller, if the cache is hit none of them will be executed.

Resources