I am building a Rails 3.2.14 app and I need to generate data from the database.
In this system I got 2 models (Project and Timereport).
Timereport is a polymorphic model (timereportable) and it got a table called total_time (in seconds).
Project has_many timereports.
What I need to achieve is to print out the total time for each projects split out on a week.
Like the illustration below:
-------------------------------------------------------------
| PROJECT | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Total |
-------------------------------------------------------------
| Drill | 2.0 | 2.0 | 2.0 | 2.0 | 2.0 | 2.0 | 2.0 | 14.0 |
-------------------------------------------------------------
| Saw | 1.0 | 2.0 | 2.0 | 0.0 | 0.0 | 2.0 | 2.0 | 9.0 |
-------------------------------------------------------------
I tried it like this and it works but it feels very uneffective.
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Project</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
<th>Total</th>
</tr>
<tbody>
<% projects.each do |project| %>
<%
data = project.timereports.group("date(created_at)")
data = data.created_between(Time.zone.now.beginning_of_week, Time.zone.now.end_of_week)
data = data.order("date(created_at) ASC")
data = data.select("date (created_at) as date, sum(total_time) as seconds")
data.each do |post|
day = Date.parse(post[:date]).strftime("%A")
if (weekday == "Monday")
#days[:mon] += seconds
elsif (weekday == "Tuesday")
#days[:tue] += seconds
elsif (weekday == "Wednesday")
#days[:wed] += seconds
elsif (weekday == "Thursday")
#days[:thu] += seconds
elsif (weekday == "Friday")
#days[:fri]+= seconds
elsif (weekday == "Saturday")
#days[:sat] += seconds
elsif (weekday == "Sunday")
#days[:sun] += seconds
end
end
%>
<tr>
<td><%= link_to project.title.capitalize, admin_projects_path(project) %></td>
<td><%= split_time_simple #days[:mon] %></td>
<td><%= split_time_simple #days[:tue] %></td>
<td><%= split_time_simple #days[:wed] %></td>
<td><%= split_time_simple #days[:thu] %></td>
<td><%= split_time_simple #days[:fri] %></td>
<td><%= split_time_simple #days[:sat] %></td>
<td><%= split_time_simple #days[:sun] %></td>
<td><%= split_time_simple #days[:mon] + #days[:tue] + #days[:wed] + #days[:thu] + #days[:fri] + #days[:sat] + #days[:sun] %></td>
</tr>
<% end %>
</tbody>
</table>
Update
The above code "works" but I suspect that it is deeply inefficient. Is there a better way?
It's not optimal solution (I use weekly_report and not sure if Rails will cache it, probably not) but way better that original.
project.rb:
def weekly_report
self.timereports.group("date(created_at)") \
.created_between(Time.zone.now.beginning_of_week, Time.zone.now.end_of_week) \
.order("date(created_at) ASC") \
.select("date (created_at) as date, sum(total_time) as seconds")
end
controller:
#projects = Project.all # or whatever else the criteria is
view:
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tbody>
<% projects.each do |project| %>
<tr>
<td><%= link_to project.title.capitalize, admin_projects_path(project) %></td>
<%= project.weekly_report.each do |day|
<td><%= split_time_simple day[:seconds] %></td>
<% end %>
<td><%= split_time_simple project.weekly_report.inject(0) { |sum, n| sum + n[:seconds] } %></td>
</tr>
<% end %>
</tbody>
</table>
Related
How to iterate each value which retrieve from DB and display them in UI?
Below the code I am trying
Controller
def execution_results
executionId1=params['executionId1']
executionId2=params['executionId2']
execution_results1 = ExecutionResult.where(:execution_id => executionId1).pluck(:parametersname,:actual_value)
execution_results2 = ExecutionResult.where(:execution_id => executionId2).pluck(:parametersname,:actual_value)
puts execution_results1
puts execution_results2
end
Now getting below response for execution_results1 and execution_results2 in Controller.
7.0ms) SELECT "execution_results"."parametersname", "execution_results"."actual_value" FROM "execution_results" WHERE "execution_results"."execution_id" = ? [["execution_id", 8]]
(0.1ms) SELECT "execution_results"."parametersname", "execution_results"."actual_value" FROM "execution_results" WHERE "execution_results"."execution_id" = ? [["execution_id", 9]]
Device.usage 12
Device.name A1
Device.number 12345
Device.usage 13
Device.name A1
Device.number 12346
Now requirement is to compare above result and show them in Ui as below.Can anyone please help how to bring like this?
|S.No |Param Name |Value|Param Name |Value|Matched|
| 1. Device.usage 12 Device.usage 13 No
| 2. Device.name A1 Device.name A1 Yes
Assuming execution_results1 and execution_results2 have the same number of records,
You can show the results in above-mentioned format by following lines in view
<table>
<tr>
<th>Sr.no</th>
<th>Param Name</th>
<th>Value</th>
<th>Param Name</th>
<th>Value</th>
<th>Matched</th>
</tr>
<% #execution_results.each do |result, index| %>
<tr>
<td><%= index + 1 %></td>
<td><%= result.name %></td>
<td><%= result.value %></td>
<td><%= #execution_results2[index].name %></td>
<td><%= #execution_results2[index].value %></td>
<td><%= compare_function(result, #execution_results2[index]) %></td>
</tr>
<% end %>
</table>
compare_function here is a helper function which will be in your controller's helper and will look something like below
(execution_results1.usage == execution_results2.usage) && (execution_results1.number == execution_results2.number)
OR
Whatever condition you want to compare
Don't forget to change
execution_results1, execution_results
to
#execution_results1, #execution_results2.to_a
in your controller
I'm pretty new to Ruby on Rails and Ruby in general but I'm trying to make a small website with simple database in Ruby on Rails.
At the moment I have the html.erb pages to show, add and edit records.
The next thing i wanted to do is the action that redirects user to a page with more info about the record he clicked in the record table.
I can't really think of any way to do this.
Any help would be really appriciated.
p.s. Sorry for any mistakes in my English - it's not my first language and im still learning!
Here is my html code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tablecontainer">
<table class="table table-bordered table-condensed">
<tr class="success">
<td><b>Nazwa</b></td>
<td><b>Obrażenia</b></td>
<td><b>Typ</b></td>
<td><b>Waga</b></td>
<td><b>Zasięg</b></td>
<td><b>Szybkość</b></td>
<td><b>Rzadkość</b></td>
<td><b>Opcje</b></td>
</tr>
<% #biala.each do |b| %>
<tr>
<td><%= b.nazwa %></td>
<td><%= b.obrazenia %>%</td>
<td><%= b.typ %></td>
<td><%= b.waga %></td>
<td><%= b.zasieg %></td>
<td><%= b.szybkosc %></td>
<td><%= b.rzadkosc %></td>
<td><%= link_to '', {id: b.id, action: 'db_wiecejbiala'}, class: "glyphicon glyphicon-info-sign" %><%= link_to '', {id: b.id, action: 'db_edytujbiala'}, class: "glyphicon glyphicon-pencil" %> <%= link_to '', {id: b.id, action: 'usunbiala'}, data: {confirm: 'Jesteś tego pewien?'}, class: "glyphicon glyphicon-remove" %></td>
</tr>
<% end %>
</table>
And here is the controller:
class BazaController < ApplicationController
def db_bronbiala
#biala = BronBiala.all
#iloscbiala = BronBiala.count
end
def db_dodajbiala
#nowybiala = BronBiala.new
end
def utworzbiala
#nowybiala = BronBiala.new(parametrybiala)
if #nowybiala.save
redirect_to(action: 'db_bronbiala')
else
render('db_dodajbiala')
end
end
def parametrybiala
params.require(:bron_biala).permit(:nazwa, :obrazenia, :typ, :waga, :zasieg, :szybkosc, :rzadkosc, :zalety, :wady, :ciekawostki, :opis)
end
def usunbiala
usuwaniebiala = BronBiala.find(params[:id]).destroy
#biala = BronBiala.all
render('db_bronbiala')
end
def db_edytujbiala
#biala = BronBiala.all
#edytowanabiala = BronBiala.find(params[:id])
end
def aktualizujbiala
#biala = BronBiala.all
#edytowanabiala = BronBiala.find(params[:id])
if #edytowanabiala.update_attributes(parametrybiala)
redirect_to(action: 'db_bronbiala')
else
render('db_edytujbiala')
end
end
def db_wiecejbiala
#biala = BronBiala.all
#bialawiecej = BronBiala.find(params[:id])
end
end
And the db_bialawiecej code:
<div class="content">
<h2>Lista:</h2>
<div class="tablecontainer">
<table class="table table-bordered table-condensed">
<tr class="success">
<td><b>Nazwa</b></td>
<td><b>Obrażenia</b></td>
<td><b>Typ</b></td>
<td><b>Waga</b></td>
<td><b>Zasięg</b></td>
<td><b>Szybkość</b></td>
<td><b>Rzadkość</b></td>
</tr>
<% #bialawiecej.id do |b| %>
<tr>
<td><%= b.nazwa %></td>
<td><%= b.obrazenia %>%</td>
<td><%= b.typ %></td>
<td><%= b.waga %></td>
<td><%= b.zasieg %></td>
<td><%= b.szybkosc %></td>
<td><%= b.rzadkosc %></td>
</tr>
<% end %>
</div>
</div>
On click send id of clicked item (GET). you will have link similar to : localhost:3000/desired_model/5
then in action do #desired_model = DesiredModel.find(params[:id])
redirect user to desired show page.
Show data.
Next time please provide some code :)
I did a query in MySql but is working in Rails and mysql2 gem.
Here is the information:
http://sqlfiddle.com/#!2/9adb8/6
The query is working fine without problems and showing this result:
UNIT V1 A1 N1 V2 A2 N2 V3 A3 N3 V4 A4 N4 V5 A5 N5
LIFE 2 0 0 1 2 0 0 0 0 0 0 0 0 0 0
ROB 0 1 0 0 1 2 0 0 0 0 0 0 0 0 0
-Installed mysql2 gem for rails 2.3.8
gem install mysql2 -v0.2.6
-Created the controller:
class PolicyController < ApplicationController
def index
#result = ActiveRecord::Base.connection.execute("select distinct #sql := concat('SELECT pb.name as unit,',group_concat(concat('SUM(CASE WHEN p.state =0 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS v',id,',SUM(CASE WHEN p.state =1 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS a',id,',SUM(CASE WHEN p.state =2 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS n',id)),' FROM cia_ensures ce LEFT JOIN policies p on ce.id = p.cia_ensure_id INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id AND ca.id=1 Group by p.policy_business_unit_id') from cia_ensures where id in(1,2,3,4,5);")
#result2 = ActiveRecord::Base.connection.execute("prepare stmt from #sql;")
#result3 = ActiveRecord::Base.connection.execute("execute stmt;")
end
end
Here is the log:
SQL (0.9ms) select distinct #sql := concat('SELECT pb.name as unit,',group_concat(concat('SUM(CASE WHEN p.state =0 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS v',id,',SUM(CASE WHEN p.state =1 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS a',id,',SUM(CASE WHEN p.state =2 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS n',id)),' FROM cia_ensures ce LEFT JOIN policies p on ce.id = p.cia_ensure_id INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id AND ca.id=1 Group by p.policy_business_unit_id') from cia_ensures where id in(1,2,3,4,5);
SQL (0.9ms) prepare stmt from #sql;
SQL (0.2ms) execute stmt;
Here is the view (is working fine and without problems but seems to be too long write several times the same code)
<table>
<% #result3.each do |policy| %>
<tr>
<td><%= policy[0] %></td>
<td><%= policy[1] %></td>
<td><%= policy[2] %></td>
<td><%= policy[3] %></td>
<td><%= policy[4] %></td>
<td><%= policy[5] %></td>
...
</tr>
<%end%>
</table>
I tried to use inspect but it shows all the information in one td and not on each td:
<% #result3.each do |policy| %>
<tr>
<td align="center"><%= policy.inspect %></td>
</tr>
<%end%>
How can I do to show all this without writing lots of lines?
Is it possible to make this in one line? without writing <%= policy[#NUMBER] %>
Please somebody can help me with this?
I will really appreciate it.
Hmmm, might have missunderstood your question since it looks really simple, are you trying to shorten this?
Change:
<td><%= policy[0] %></td>
<td><%= policy[1] %></td>
<td><%= policy[2] %></td>
<td><%= policy[3] %></td>
<td><%= policy[4] %></td>
<td><%= policy[5] %></td>
To:
<% policy.each do |p| %>
<td><%= p %></td>
<% end %>
Do this
<% #result3.each do |policy| %>
<tr>
<% policy.each { |p| raw "<td>#{p}</td>" } %>
</tr>
<%end%>
Just iterate over each collection in each policy object.
<table>
<% #result3.each do |policy| %>
<tr>
<%policy.each do |item| %>
<td><%= item %></td>
<%end%>
</tr>
<%end%>
</table>
Hello my fellow programmers, I am a ruby on rails noob and need some help:
Based on today's date I am querying the db and getting the results as an array.
#cr = [#<CRate id: 1, currency: "AUD", rate: 2.0, datetime: "2013-10-09 22:59:59">,
#<CRate id: 7, currency: "USD", rate: 10.0, datetime: "2013-10-09 29:50:50">,
#<CRate id: 9, currency: "EUR", rate: 20.0, datetime: "2013-10-09 22:59:59">,
#<CRate id: 12, currency: "RUB", rate: 12.0, datetime: "2013-10-09 22:59:59">,
#<CRate id: 14, currency: "AUD", rate: 18.0, datetime: "2013-10-09 29:50:50">]
Question: I need to dynamically display the table based on currency(header), depending on the time, if rate exist then I display it else output is nil. Like this table below:
I have tried to do this:
<table>
<thead>
<th>Time</th>
<% #currency = #cr.collect(&:currency) %>
<% #currency.each do |cur| %>
<th><%= cur %></th>
<% end %>
</thead>
<tbody>
<tr class="<%= cycle('odd', 'even') %>">
<td><%= #datetime = #cr.collect(&:datetime) %></td>
<% #rate = #cr.collect(&:rate) %>
<% #rate.each do |r| %>
<td><%= r %></td>
<% end %>
</tr>
</tbody>
</table>
This doesn't work because the thead is updated with 2 AUD's and I don't know how to proceed. Please help.
Thanks a lot.
First, you need unique currency types, so line no. 4 will be:
<% #currency = #cr.collect(&:currency).uniq %>
Secondly, you need to get rates based on datetime and currency type (since you have not specified Rails version, I will try and write a working solution which might not be best solution):
<tbody>
<% #datetime = #cr.collect(&:datetime).uniq %>
<% #datetime.each do |dt| %>
<tr class="<%= cycle('odd', 'even') %>">
<td><%= dt %></td>
<% #currency.each do |curr| %>
<td><%= #cr.select {|o| o.currency == curr && o.datetime == dt}.rate %></td>
<% end %>
</tr>
<% end %>
</tbody>
HTH
Edit: This seems to be an inefficient way to solve this problem because you are relying too much on arrays in a way that they will always come in order you are expecting. I would like rather create a Hash (better known as key-value pair) of #cr like {'first_datetime' => {'AUD' => '10', 'RUB' => '20'}, 'second_datetime' => {'AUD' => '50', 'RUB' => ''}} and so forth.
Edit 2: In your controller, create a hash and 2 sets like:
#currencies = Set.new
#datetimes = Set.new
#currency_rate_datewise = Hash.new {|h, k| h[k] = {}}
#cr.each do |cr|
#currencies.add cr.currency
#datetimes.add cr.datetime
#currency_rate_datewise[cr.datetime][cr.currency] = cr.rate
end
Now your view could be simplified to:
<table>
<thead>
<th>Time</th>
<% #currencies.each do |cur| %>
<th><%= cur %></th>
<% end %>
</thead>
<tbody>
<% #datetimes.each do |datetime| %>
<tr class="<%= cycle('odd', 'even') %>">
<td><%= datetime %></td>
<% #currencies.each do |currency| %>
<td><%= #currency_rate_datewise[datetime][currency] || 'nil' %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
Although, I would have used group_by selectively, but I guess, it is better if you stick with learning such things at beginner's stage. I have written this from top of my head, please post a comment if something's wrong.
HTH
you can use the group_by rails helper for that. see the documentation:
group_by() Collect an enumerable into sets, grouped by the result of a
block. Useful, for example, for grouping records by date.
Example:
latest_transcripts.group_by(&:day).each do |day, transcripts|
p "#{day} -> #{transcripts.map(&:class).join(', ')}"
end
"2006-03-01 -> Transcript"
"2006-02-28 -> Transcript"
"2006-02-27 -> Transcript, Transcript"
"2006-02-26 -> Transcript, Transcript"
"2006-02-25 -> Transcript"
"2006-02-24 -> Transcript, Transcript"
"2006-02-23 -> Transcript"
I am trying to make a table with ten values across on each row starting at 1 and going to 100.
My Ruby code looks like this:
<table border="1">
<% (1..100).each do |i|
d3 = (i % 3 == 0)
d5 = (i % 5 == 0)
i = "<b>#{i}</b>" if d5
i = "<i>#{i}</i>" if d3 %>
<tr>
<td><%= i %></td>
</tr>
<% end %>
</table>
How would I put this in an HTML table in a 10 X 10?
Using ERB:
<table>
<%10.times do |row|%>
<tr>
<%10.times do |col|%>
<td><%=
i = row*10+col+1
if i%5==0
"<b>#{i}</b>"
elsif i%3==0
"<i>#{i}</i>"
else
i
end
%></td>
<%end%>
</tr>
<%end%>
</table>
Using Haml:
%table
- 10.times do |row|
%tr
- 10.times do |col|
%td
- i = row*10+col+1
= i%5==0 ? "<b>#{i}</b>" : i%3==0 ? "<i>#{i}</i>" : i
<table border="1">
<% (1..100).each do |i|
d3 = (i % 3 == 0)
d5 = (i % 5 == 0)
s = "#{i}"
s = "<b>#{i}</b>" if d5
s = "<i>#{i}</i>" if d3 %>
<% if i % 10 == 1 %><tr><% end %>
<td><%= s %></td>
<% if i % 10 == 0 %></tr><% end %>
<% end %>
</table>
Basically, you want to start a table row before elements 1, 11, 21, etc. and end a row after elements 10, 20, 30, etc.