serial number with pagination rails - ruby-on-rails

I am using pagination for my index page where I list all the users information like name, email etc. In the table I want to display the serial number in the order [1,2,3...]. If I user the user_id and if I delete the user the number will be missing out of sequence. I use the following code in my view
<% #user.each_with_index do |d, i| %>
<tr>
<td><%= i+1 %></td>
<% if d.profile.present? %>
<td><%= link_to d.profile.first_name+ " "+d.profile.last_name, posts_individualpostlink_path(:id => d.id) %> </td>
<% else %>
<td><%= "No Profile" %></td>
<% end %>
<td><%= d.email %></td>
<% if d.profile.present? %>
<td><%= d.profile.date_of_birth %> </td>
<% else %>
<td><%= "No Profile" %></td>
<% end %>
</tr>
<% end %>
</table>
<%= will_paginate #user %>
when I am going to the second page again the serial number starts with [1,2,....]. Per Page if i am giving 10 users, the second page should show [11, 12, 13,..... in the table.
Can anyone help me to do this. Thanks

Try with
<%
count = ((params[:page] || 1).to_i - 1) * 10
#user.each_with_index do |d, i| %>
<tr>
<td><%= count + i %></td>

Before answering question, small emotional note: stop using single letter variables in Your code. It makes it completely unreadable.
Why not use <% #user.each_with_index do |user, idx| %> ? Now in You code block it's easy to understand that You always refer to user.
Now the answer. Will paginate add page parameter to the paging links. So in You controller You should be able to do this:
#page = params[:page] || 1
After that use it to calculate correct number in Your view:
<td><%= (#page - 1) * number_of_items_on_page + i+1 %></td>

Related

Rails: Highlight the last record inside a loop

I'm trying to highlight the last entry inside a loop. But the following code assigns id="highlight" to every table row :(
<% #sales.order("created_at desc").each do |sale| %>
<tr <% if sale.created_at = Sale.last %>id="highlight"<% end%> >
<td><%= sale.user.name %></td>
<td><%= sale.product %></td>
....
Any ideas? Thank you guys!
if sale.created_at = Sale.last
should be
if sale.created_at == Sale.last.created_at
Alternatively, I guess the following would be better, since it eliminates an additional query Sale.last:
<% #sales.order("created_at desc").each_with_index do |sale, idx| %>
<tr <% if idx == #sales.length - 1 %>id="highlight"<% end%> >
<td><%= sale.user.name %></td>
<td><%= sale.product %></td>
....
HTH
To get the number of rows (without an additional db query), you can use:
#sales.length
Then use each_with_index for your loop:
<% #sales.order("created_at desc").each_with_index do |sale, i| %>
<tr <% if #sales.length == i + 1 %>id="highlight"<% end%> >
<td><%= sale.user.name %></td>
<td><%= sale.product %></td>
</tr>
<% end %>
Check the way you are using the = sign.
Note that equality(==) is different from assignment(=).
What you need is the equality sign(==) here. so:
<% if sale.created_at == Sale.last %>id="highlight"<% end%>
as opposed to:
<% if sale.created_at = Sale.last %>id="highlight"<% end%>
which you are doing.

Gracefully jumping to next record - ActiveRecord

Rails 3.2
I have the following in my view:
<% #organizations.each do |o| %>
<% organization = Organization.find(o.organization_id) %>
<% if organization == nil %>
<% next %>
<% end %>
<tr>
<td><%= o.org_name %></td>
<td><%= number_to_currency(o.revenue, :precision => 0) %></td>
<td><%= o.rank %></td>
</tr>
<% end %>
I was under the impression that if organization is not found, execution would jump to the next record. Instead, I am getting the "something went wrong".
Looking through the log file, one of the organization_id is not found in the organizations table, and that's what's triggering the error.
Why isn't execution jumping to the next record?
Temporary Solution: I changed
<% organization = Organization.find(o.organization_id) %>
To:
<% organization = Organization.find_by_id(o.organization_id) %>
and that gives me a nil when it does not find anything. If it's nil, the execution skips to the next record
According to http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find, Organization.find(o.organization_id) will raise an ActiveRecord::RecordNotFound for the id that does not exist in the table.
Addendum:
Try something like the following:
<% ids = #organizations.map(&:organization_id) %>
<% organizations = Organization.where(id: ids) %>
<% organizations.each do |o| %>
<tr>
<td><%= o.org_name %></td>
<td><%= number_to_currency(o.revenue, :precision => 0) %></td>
<td><%= o.rank %></td>
</tr>
<% end %>
With this method, you'll fetch all the organizations with 1 query from the DB as opposed to 1 for every organization.

List two columns on ruby

Trying to show a list of items. I have items and calibrations. I want show all the data from items + date_cal_expired (select the max date, because one item can have many calibrations) from calibrations.
In the controller
#items = Item.includes(:calibrations).where('calibrations.date_cal_expired <= ?' , now)
In the index
<% #items.each do |item| %>
<tr>
<td><%= item.den_cont %></td>
<td><%= item.marca %></td>
<td><%= item.modelo %></td>
<td><%= item.nro_serie %></td>
<td><%= item.genre.genre %></td>
<td><%= item.state.state %></td>
What should I do to show date_cal_expired??
I don't know how to show data from other table
Hope you understand. Tks!
If you want to perform single query:
Item.select("items.*, c.date_cal_expired AS date_cal_expired")
.joins("LEFT JOIN calibrations AS c ON c.item_id = item.id
WHERE NOT EXISTS(SELECT 1 FROM calibrations AS j
WHERE c.item_id = j.item.id
AND t.date_cal_expired < j.date_cal_expired)")
Now the date_cal_expired is an item's attribute:
<% item.date_cal_expired %>
Or simple solution:
<% item.calibrations.map(&:date_cal_expired).try(:max) %>
item.calibrations.pluck(:date_cal_expired).max
You have already showed data from other table by using
<td><%= item.genre.genre %></td> // this way you go to table genre and display field genre
If you want data from other table you should just put
<td>
<% item.calibrations.each do |calibration| %>
<%= calibration.field_1 %>
// ....
<%= calibration.field_n %>
<% end %>
</td>
item.calibrations.max("your value")

Is there a way to save crawled information?

The user of my application submits a request via a form and receives a set of numbers. The numbers constantly update throughout the day and I need a way to track the average of the last two numbers.
It'll work something like this:
How much experience do you have now?: 13000000
How much experience do you have now?: 13200000 (one hour later)
Then the user should be redirected to a page where the "experience per hour" is displayed: 200000
My application can currently only make the request for the number. Now I need a way to save that number and the time it was created, allow for a second number to be searched, and then perform a computation on them.
Here are the contents of my files.
home.html.erb with the form:
<h1>Welcome to xpTrack</h1>
<%= form_tag("/search", method: "get") do %>
<%= label_tag(:username, "Search for:") %>
<%= text_field_tag(:username) %>
<%= submit_tag("Search") %>
<% end %>
This form passes the username the user enters into params[:username] in the controller:
SearchController
class SearchController < ApplicationController
def home
require 'open-uri'
#username = params[:username]
#url = "http://hiscore.runescape.com/index_lite.ws?player=#{#username}"
#doc = Nokogiri::HTML(open(#url))
#stats = #doc.text.split(' ').map{|a| a.split(",") }
#skills = %w(overall, attack, defence, strength, constitution, ranged, prayer, magic, cooking, woodcutting, fletching, fishing, firemaking, crafting, smithing, mining, herblore, agility, thieving, slayer, farming, runecrafting, hunter, construction, summoning, dungeoneering, divination)
#max = 13034431
end
end
This view is rendered after searching:
<h1>
<%= #username.capitalize %>
</h1>
<table>
<tr>
<th>Skill</th>
<th>Rank</th>
<th>Level</th>
<th>Experience</th>
<th>Experience to 99</th>
</tr>
<% #skills.each_with_index do |skill, i| %>
<tr>
<td><%= skill.chomp(',').capitalize %></td>
<td><%= #stats[i][0] %></td>
<td><%= #stats[i][1] %></td>
<td><%= #stats[i][2] %></td>
<% if #stats[i][2].to_i < #max %>
<td><%= #max - (#stats[i][2]).to_i %></td>
<% end %>
</tr>
<% end %>
</table>
Link to the application at Heroku: http://runescapecalc.herokuapp.com/
When searching, use the username 'Brink'.

Rails undefined method `hospital' for nil:NilClass

Respected ppl ...
In my application i want to display the last hospital name for a given employee ...
for which i tried this :
<%= #employee.postings.last.hospital.hospital_name %>
All the required associations are correct ...as this works perfectly for all the employees who have a posting ... but i get the error for the employees who dont have even a single posting ...
I tried doing
<%= #employee.postings.last.hospital.hospital_name.to_s %>
and even
<% if !#employee.postings.last.hospital.nil? %>
and even a "try" function ....
I just want it to not display any data when there dosent exist one ... instead of the intimidating error ...
if i could just learn how to skip over printing nil values then it would be awesome ..as i am facing similar issues elsewhere too ...
For ex :
in my employees main page i want to display all the qualifications for each employee for which im doing :
<tbody>
<% #employees.each do |employee| %>
<tr>
<td><%= employee.emp_id %></td>
<td><%= employee.emp_treasury_id %></td>
<td><%= link_to employee.emp_full_name,employee_path(employee) %></td>
<% #employee.qualifications.each do |qualification| %>
<td><%= qualification.qualification_name.Qualification_name %></td>
<% end %>
</tr>
<% end %>
but i end up getting "undefined method `qualifications' for nil:NilClass" error once again ...
Im trying a lot ... but still ...
Thanx and Sincere Regards
-Sky
Try this
<%= #employee.postings.last.try(:hospital).try(:hospital_name) || "N/A" %>
using try
<%= #employee.postings.last.try(:hospital).try(:hospital_name) %>
using if
<%= #employee.postings.last.hospital.hospital_name if #employee.postings.exists? && #employee.positings.last.hospital %>
It should be
employee not #employee
Rest you use try or respond_to for being more safe. As you might not have run the migrations.
.respond_to?(:field) && model.try(:field)
Thanks
<% #employees.each do |employee| %>
<tr>
<td><%= employee.emp_id %></td>
<td><%= employee.emp_treasury_id %></td>
<td><%= link_to employee.emp_full_name,employee_path(employee) %></td>
<% employee.qualifications.each do |qualification| %>
<td><%= qualification.try(:qualification_name).try(:Qualification_name) %></td>
<% end %>
</tr>
<% end %>

Resources