Rails 4 multi table join with data from all tables - ruby-on-rails

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>

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

Populating a table using JSON from the database in Rails

I have the following JSON stored in my database under an column called event (using the json column type).
{
"captable":{
"id":28,
"version":1,
"name":"CapTable",
"company_id":22,
"created_at":"2018-10-31T18:56:03.965Z",
"updated_at":"2018-10-31T18:57:30.626Z",
"total_stocks_in_company":"400.0"
},
"event":{
"status_locked":null,
"id":51,
"price_per_share":"1000.0",
"total_company_stocks_after_event":"400.0",
"name":"2nd event ",
"date":"2018-10-31",
"currency":"SEK",
"valuation":"400000.0",
"created_at":"2018-10-31T18:57:17.282Z",
"updated_at":"2018-10-31T18:57:30.676Z",
"captable_id":28,
"company_id":22,
"snapshot":"{\"captable\":{\"id\":28,\"total_stocks_in_company\":\"400.0\",\"version\":1,\"name\":\"CapTable\",\"company_id\":22,\"created_at\":\"2018-10-31T18:56:03.965Z\",\"updated_at\":\"2018-10-31T18:57:30.626Z\"},\"event\":{\"status_locked\":null,\"id\":51,\"price_per_share\":\"1000.0\",\"total_company_stocks_after_event\":\"400.0\",\"name\":\"2nd event \",\"date\":\"2018-10-31\",\"currency\":\"SEK\",\"valuation\":\"400000.0\",\"created_at\":\"2018-10-31T18:57:17.282Z\",\"updated_at\":\"2018-10-31T18:57:30.665Z\",\"captable_id\":28,\"company_id\":22,\"snapshot\":null},\"shareholders\":[{\"id\":52,\"shareholder\":\"Peter\",\"name\":\"Peter\",\"number_of_stocks\":\"100.0\",\"company_id\":22,\"created_at\":\"2018-10-31T18:55:42.730Z\",\"updated_at\":\"2018-10-31T18:57:30.637Z\",\"ownership_percentage\":\"0.25\",\"email\":\"\",\"telephone\":\"\"},{\"id\":53,\"shareholder\":\"Jane\",\"name\":\"Jane\",\"number_of_stocks\":\"100.0\",\"company_id\":22,\"created_at\":\"2018-10-31T18:55:49.490Z\",\"updated_at\":\"2018-10-31T18:57:30.644Z\",\"ownership_percentage\":\"0.25\",\"email\":\"\",\"telephone\":\"\"},{\"id\":54,\"shareholder\":\"Sally\",\"name\":\"Sally \",\"number_of_stocks\":\"200.0\",\"company_id\":22,\"created_at\":\"2018-10-31T18:55:56.192Z\",\"updated_at\":\"2018-10-31T18:57:30.651Z\",\"ownership_percentage\":\"0.5\",\"email\":\"\",\"telephone\":\"\"}]}"
},
"shareholders":[
{
"id":52,
"shareholder":"Peter",
"name":"Peter",
"number_of_stocks":"50.0",
"company_id":22,
"created_at":"2018-10-31T18:55:42.730Z",
"updated_at":"2018-10-31T18:58:31.406Z",
"ownership_percentage":"0.125",
"email":"",
"telephone":""
},
{
"id":53,
"shareholder":"Jane",
"name":"Jane",
"number_of_stocks":"150.0",
"company_id":22,
"created_at":"2018-10-31T18:55:49.490Z",
"updated_at":"2018-10-31T18:58:31.410Z",
"ownership_percentage":"0.375",
"email":"",
"telephone":""
},
{
"id":54,
"shareholder":"Sally",
"name":"Sally ",
"number_of_stocks":"200.0",
"company_id":22,
"created_at":"2018-10-31T18:55:56.192Z",
"updated_at":"2018-10-31T18:57:30.651Z",
"ownership_percentage":"0.5",
"email":"",
"telephone":""
}
]
}
I can successfully render the JSON to my view using
<%= #event.snapshot %>
However, what I'd like to do now is fill a table in my view using the json column as the data source, but I'm having trouble figuring out where to put the logic, whether ot have it in the view of have a separate method in either the controller or model.
What I'd love to do is have a table that looks like this: (pseudocode)
<table class="table">
<tr>
<th>Shareholder</th>
<th>Name</th>
<th>Number of Shares</th>
<th>Ownership %</th>
</tr>
<%= #event.snapshot["shareholders"].each do |shareholder| %>
<tr>
<td><%= shareholder.shareholder %></td>
<td><%= shareholder.name %></td>
<td><%= shareholder.number_of_stocks %></td>
<td><%= shareholder.ownership_percentage %></td>
</tr>
<%= end %>
</table>
Can someone help point me in the right direction when it comes to filling a table using a json object instead of simply values from the database?
To clarify: how should I best access the shareholders when iterating through the JSON (i.e. <%= #event.snapshot["shareholders"].each do |shareholder| %> ) in order to create a new table row for each of them?
If you have a Shareholder model with the necessary attributes you can use the JSON to populate objects and then do pretty much what you did above. Note: the first line of the loop now creates a new object for each shareholder entry.
You'll need to parse the JSON first.
<% snapshot_json = JSON.parse(#event.snapshot) %>
<% snapshot_json["shareholders"].each do |shareholder_hash| %>
<% shareholder = Shareholder.new(shareholder_hash) %>
<tr>
<td><%= shareholder.shareholder %></td>
<td><%= shareholder.name %></td>
<td><%= shareholder.number_of_stocks %></td>
<td><%= shareholder.ownership_percentage %></td>
</tr>
<%= end %>
If you don't want to create a new class/model you can just use the hash form of the JSON directly ...
<% snapshot_json = JSON.parse(#event.snapshot) %>
<% snapshot_json["shareholders"].each do |shareholder| %>
<tr>
<td><%= shareholder["shareholder"] %></td>
<td><%= shareholder["name"] %></td>
<td><%= shareholder["number_of_stocks"] %></td>
<td><%= shareholder["ownership_percentage"] %></td>
</tr>
<%= end %>

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.

RoR: how make query to return the sum values for each group?

been teaching myself how to build a simple ruby/rails site. trying now to figure out the caveats for data manipulation. group is working, how do i "sum" all the columns?
index.html.erb
<table>
<tr>
<th>Site</th>
<th><7days</th>
<th>>7days</th>
<th>>30days</th>
<th>>90days</th>
<th>>180days</th>
<th>>365days</th>
</tr>
<tr>
<% #gdcomets.each do |dcomet| %>
<td><%= dcomet.site %></td>
<td><%= #sum1 %></td>
<td><%= #sum2 %></td>
<td><%= #sum3 %></td>
<td><%= #sum4 %></td>
<td><%= #sum5 %></td>
<td><%= #sum6 %></td>
</tr>
<% end %>
</table>
dcomets_controller
class DcometsController < ApplicationController
# GET /dcomets
# GET /dcomets.json
def index
#dcomets = Dcomet.all
#gdcomets = Dcomet.group(:site)
#sum1 = #gdcomets.map(&:ls7day).sum
#sum2 = #gdcomets.map(&:gt7day).sum
#sum3 = #gdcomets.map(&:gt30day).sum
#sum4 = #gdcomets.map(&:gt90day).sum
#sum5 = #gdcomets.map(&:gt180day).sum
#sum6 = #gdcomets.map(&:gt365day).sum
respond_to do |format|
format.html # index.html.erb
format.json { render json: #gdcomets }
end
end
end
#sum = #gdcomets.map(&:data).sum
:data being the name of the column you want to sum.
You'll get better performance letting SQL do the donkey work of summing everything:
Dcomet.group(:site).sum(:data)
Where :data is the name of column you want to sum. That will return a hash with the keys being the site values, and the values the corresponding sum for that site

Display data in table cells from database table Ruby on Rails

I want to display some data from a table and display it in the table cells. I have the following.
Controller
#data = HospitalBooking.where(:created_at => #date_range)
#stuff = []
#stuff[0] = []
index = 0
#stuffs.each do |stuff|
#rotated[0][index] = stuff.detail0
index += 1
end
Not sure if I have gone about this the correct way also how would I display it in my view
If I understood it right, you want to display the result of a query in a html table.
Here is your query, in your controller:
#data = HospitalBooking.where(:created_at => #date_range)
In your view
<table>
<tr>
<th>field1</th>
<th>field2</th>
</tr>
<% #data.each do |data| %> #start loop
<tr>
<td><%= data.field1 %></td> #column field1 in your database
<td><%= data.field2 %></td> #column field2 in your database
</tr>
<% end %> #end loop
</table>

Resources