How can I iterate through an array in rails view? - ruby-on-rails

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>

Related

How to iterate each value which retrieve from DB and display them in UI?

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

Rails 4 multi table join with data from all tables

I think this is simple but I'm just not getting it. I need to join 3 tables and have rails return values from all 3. I have done a join but rails only returns values from 1 table. I think I just don't know the syntax
Here is my controller method
#previous_results = Test.joins(:run, :detail).where("runs.name = ? AND tests.name = ?", #run.name, #test.name).last(1000)
That does do a join here is the sql from it
SELECT `tests`.* FROM `tests` INNER JOIN `runs` ON `runs`.`id` = `tests`.`run_id` INNER JOIN `details` ON `details`.`test_id` = `tests`.`id`
WHERE (runs.name = 'SNMSubscriberSpecificTemplatesFeedsTest' AND tests.name = 'testSitePrefixFalseForNTINSequentialList') ORDER BY `tests`.`id` DESC LIMIT 1000
all I need to do is return values from the details table also. I want 2 column values from details essentially instead of doing test .* I was test.id, test.name, detail.text, detail.message as my return
Int active record how do I tell it to not just return test table data but also include columns in details
This query in SQL does what I want I need to know how to active record it
SELECT `tests`.*, `details`.`detail_text`, `details`.`detail_error`
FROM `tests`
INNER JOIN `runs` ON `runs`.`id` = `tests`.`run_id`
INNER JOIN `details` ON `tests`.`id` = `details`.`id`
WHERE (runs.name = 'SNMSubscriberSpecificTemplatesFeedsTest' AND tests.name = 'testSitePrefixFalseForNTINSequentialList')
ORDER BY `tests`.`id` DESC LIMIT 1000
#tests = Test
.select('tests.*', 'details.detail_text', 'details.detail_error')
.joins(:run, :detail)
.where(
runs: { name: 'SNMSubscriberSpecificTemplatesFeedsTest' },
tests: { name: 'testSitePrefixFalseForNTINSequentialList' }
)
.limit(1000)
.order(id: :desc)
your views would look like:
<table>
<tr>
<th>Test ID</th>
<th>Test Detail's Detail Text</th>
<th>Test Detail's Detail Error</th>
</tr>
<% #tests.each do |test| %>
<tr>
<td><%= test.id %></td>
<td><%= test.detail_text %></td>
<td><%= test.detail_error %></td>
</tr>
<% end %>
</table>
Recommendation:
do not use select() explicitly to fetch the "associated values", but instead access them directly through the objects, like below
#tests = Test
.joins(:run, :detail).includes(:detail)
.where(
runs: { name: 'SNMSubscriberSpecificTemplatesFeedsTest' },
tests: { name: 'testSitePrefixFalseForNTINSequentialList' }
)
.limit(1000)
.order(id: :desc)
your views would look something like:
<table>
<tr>
<th>Test ID</th>
<th>Test Detail's Detail Text</th>
<th>Test Detail's Detail Error</th>
</tr>
<% #tests.each do |test| %>
<tr>
<td><%= test.id %></td>
<td><%= test.detail.detail_text %></td>
<td><%= test.detail.detal_error %></td>
</tr>
<% end %>
</table>

undefined method `txnid' for []:Array

I am trying to display the unique trasactions in my table. Actually I have some duplicate transactions as well. I am getting this below error when I call txnid.uniq on my table.(#all_settlement_details)
undefined method `txnid' for []:Array
Transaction.html.erb
<tr>
<th>Merchant Name</th>
<th>Transaction ID</th>
<th>Payment Mode</th>
<th>Amount</th>
<th>Status</th>
<th>Transaction Fee</th>
<th>Discount</th>
<th>Additional Charges</th>
<th>Added On</th>
</tr>
</thead>
<tbody id="details">
<% #all_settlement_details.txnid.uniq.each do |sd| %>
<tr>
<td><%= sd.merchantname %></td>
<td><%= sd.txnid %></td>
<td><%= get_mode_ui.value(sd.mode) %></td>
<td><%= sd.amount %></td>
<td><%= get_status(sd.status) %></td>
<td><%= sd.mer_service_fee %></td>
<td><%= sd.discount %></td>
<td><%= sd.additional_charges%></td>
<td><%= get_added_on_date sd.addedon %></td>
</tr>
<% end %>
</tbody>
traansactions_helper.rb
def get_all_settlement_details
# Offset increments by 10 and Limit remains 11
_txn_filter_scope = {'transaction_status' => ["status", (params[:transaction_status].split(',') rescue nil)],
'payment_options' => ["payment_options", (params[:payment_options].split(',') rescue nil)],
'transaction_id' => ['transaction_id', params[:transaction_id]],
'transaction_amount' => ['amount_range', ((params[:transaction_amount].split(',')[0] || 0) rescue nil), ((params[:transaction_amount].split(',')[1] || 100000000) rescue nil)],
'merchant_mid' => ['merchant_mid',params[:merchant_mid]],
'merchant_name' => ['merchant_name', params[:merchant_name]],
'clicks' => ['txn_offset', ((params[:clicks].to_i)*10 rescue 0)]
}
method_array = [['settlement_details'],["date_filter", #start_date, #end_date]]
method_array << ["txn_limit", 11] unless #csv_format
method_array << ['merchant_mid', #merchant_mid] if #merchant_mid
records = call_scope_methods_dynamically(method_array, _txn_filter_scope)
records.empty? ? nil : records
end
# Get the multiple payment modes of a trasaction, if any.
def get_multiple_payment_modes txn_id, payment_modes
debugger
PG_MODE
#all_modes = []
#total_trasactions = []
_multiple_modes = {'transaction_id' => ['transaction_id', params[:transaction_id]]}
methods = [['settlement_details'],['merchant_mid'],['transaction_id'], ['payment_modes']]
#total_transactions << ['transaction_id', txn_id] if payment_modes.present?
if #total_transactions[:payment_modes] > 1
payment_modes.each do |m|
#all_modes << m
end
#all_modes
end
end
def get_uniq_transactions txn_id
#all_modes = []
uniq_tr = #all_settlement_details.txn_id.uniq
uniq_tr.payment_modes.each do |m|
#all_modess << m
end
end
How to fix this error and display only unique transactions?
Thanks for your help!
From what I'm seeing, my best guess is that you are calling txnid on an Array, obviously, you are going to see this error.
This error might be coming from your view template, where you are calling txnid on #all_settlement_details, which is not available.
What you might need is, #all_settlement_details.uniq.pluck(:txnid) instead of #all_settlement_details.txnid.uniq in your view template.
PS: I would prefer not to have this logic in the helper as it is shared across the view of the app. Instead, I would like to use a decorator(draper/hand rolled plain ruby object) here.

How to populate a week

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>

Creating a table in HTML with Ruby?

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.

Resources