Navigating jbuilder to attatch html string - ruby-on-rails

I am setting up a collection of ruby issues (#issues) into arrays using jbuilder so they plug into datatables. Normally with datatables each row represents a single record and you determine the columns by their fields (:id, :name, etc)
In this case each issue has a status (:initial, waiting_on_customer, waiting_on_user, waiting_on_supplier, closed) and is sorted in the controller so the #issues object looks like this where each "row" is comprised of 5 issues, one for each status
{
initial: {
id: 3,
priority: "Low",
status: "initial",
name: "Broken Parts",
notes: "shaft was bent",
created_at: "2020-11-20T00:45:40.000Z",
updated_at: "2020-11-23T15:39:59.000Z",
purchase_order_id: null,
deleted_at: null,
tenant_id: null,
supplier_id: null,
incoming_order_id: null
},
waiting_on_user: {
id: 8,
priority: "Medium",
status: "waiting_on_user",
name: "Poor Communication",
notes: "Supplier wont return call",
created_at: "2020-11-20T05:56:49.000Z",
updated_at: "2020-11-23T22:39:25.000Z",
purchase_order_id: null,
deleted_at: null,
tenant_id: null,
supplier_id: 2,
incoming_order_id: null
},
waiting_on_supplier: {
id: 4,
priority: "Low",
status: "waiting_on_supplier",
name: "Payment reversed",
notes: "Check bounced",
created_at: "2020-11-20T00:46:02.000Z",
updated_at: "2020-11-23T22:39:31.000Z",
purchase_order_id: null,
deleted_at: null,
tenant_id: null,
supplier_id: null,
incoming_order_id: null
},
waiting_on_customer: {
id: 1,
priority: "Medium",
status: "waiting_on_customer",
name: "Big Problem",
notes: "Mayday were going down!!",
created_at: "2020-11-20T00:44:34.000Z",
updated_at: "2020-11-23T15:42:52.000Z",
purchase_order_id: null,
deleted_at: null,
tenant_id: null,
supplier_id: null,
incoming_order_id: null
},
closed: {
id: 2,
priority: "High",
status: "closed",
name: "Lost Package",
notes: "Missing package, shipper says it was delivered",
created_at: "2020-11-20T00:45:16.000Z",
updated_at: "2020-11-23T15:39:01.000Z",
purchase_order_id: null,
deleted_at: null,
tenant_id: null,
supplier_id: null,
incoming_order_id: null
}
},
#issues gets passed to index.json.jbuilder
json.array! #issues, partial: "issues/issue", as: :issue_hash
which passes each issue_hash to the issue.json.jbuilder
json.extract! issue_hash, :initial, :waiting_on_user, :waiting_on_supplier, :waiting_on_customer, :closed
I can add the string to the base level of the issue_hash with
json.issue_card_html render 'issue_card_datatable.html.erb',i: issue
But I am trying to attach this html string to the "initial" issue object like so
# json.initial.issue_card_html render 'issue_card_datatable.html.erb',i: issue
but It gets me a no method error for issue_card_html
Ive tried every combination of looping and diving into the json objects I can think of and that are on the jbuilder docs to no avail. I think I must be missing something obvious as it shouldn't be this hard to navigate and manipulate a json object

Related

Loop through JSON Object Swift 5

I am trying to iterate through a JSON object and obtain specific values in the swift programming language.
I am receiving a JSON like so
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
let charges = json["charges"] as? [String:Any]
json:
{
object: 'list',
data: [
{
id: 'ch_1IWQEfKn7R1M6tqnhrpyIhMk',
object: 'charge',
amount: 555,
amount_captured: 555,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IWQEfKn7R1M6tqnvTHQeSEF',
application_fee_amount: 6,
balance_transaction: 'txn_1IWQEfKn7R1M6tqnkK9LCNuM',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1616090777,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IWQEeKn7R1M6tqnYbGfFCzg',
payment_method: 'pm_1IWQEeKn7R1M6tqnKLxSg6vZ',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IWQEfKn7R1M6tqnhrpyIhMk/rcpt_J8hdy05N6VfOmRECdumpti8Jiljz2Et',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
},
{
id: 'ch_1IU62QKn7R1M6tqnbXXlOpch',
object: 'charge',
amount: 5599,
amount_captured: 5599,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IU62RKn7R1M6tqnLle3zblA',
application_fee_amount: 56,
balance_transaction: 'txn_1IU62RKn7R1M6tqn3ttu9F3N',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1615536482,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IU62NKn7R1M6tqnWSOLJVge',
payment_method: 'pm_1IU62PKn7R1M6tqnIyOUgUMX',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IU62QKn7R1M6tqnbXXlOpch/rcpt_J6Id30gjIhQU6AWPBHgUXoujbhFOTyf',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
},
{
id: 'ch_1IU60cKn7R1M6tqny9o2NV5W',
object: 'charge',
amount: 1000,
amount_captured: 1000,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IU60cKn7R1M6tqn95nUHETe',
application_fee_amount: 10,
balance_transaction: 'txn_1IU60cKn7R1M6tqnZKNbSEXf',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1615536370,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IU60ZKn7R1M6tqnrUSK1TQD',
payment_method: 'pm_1IU60bKn7R1M6tqnAUHQXqJG',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IU60cKn7R1M6tqny9o2NV5W/rcpt_J6Ib5PEZQzEgyXWoOwKcxZ9x7mByCVu',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
}
],
has_more: true,
url: '/v1/charges'
}
How can I iterate through the JSON object to receive "amount", "currency", and "id".
For example PSUEDO:
for item in charges {
print(item["amount"])
print(item["currency"])
print(item["id"])
}
I may be initializing the json improperly such as
json["charges"] as? [String:Any]
You shouldn't use try ? - This throws away errors. Always use do/try/catch so that you handle any errors that occur, even if you just print them.
JSONSerialization and decoding JSON to arrays and dictionaries isn't best practice. It is much better to create suitable structs that conform to Codable and use JSONDecoder.
struct Response: Codable {
var object: String
var hasMore: Bool
var data: [ResponseData]
var url: String
enum CodingKeys: String, CodingKey {
case object
case hasMore = "has_more"
case url
case data
}
}
struct ResponseData: Codable {
var amount: Int
var currency: String
var id: String
}
For simplicity I have't added all of the properties to the ResponseData struct, just the ones you have said you are interested in
do {
let json = try JSONDecoder().decode(Response.self, from: data)
json.data.forEach { charge in
print(charge.id)
print(charge.currency)
print(charge.ammount)
}
} catch {
print("Error! \(error)")
}

Ruby loop over the dates

Hello I have Schedules table like this;
<ActiveRecord::Relation [#<Schedule id: 427, date: "2016-06-15", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 428, date: "2016-06-16", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 429, date: "2016-06-17", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 430, date: "2016-06-22", notes: "", price: "253", promo: "", status: "available", boat_id: 3, created_at: "2016-06-14 09:23:55", updated_at: "2016-06-14 09:23:55">, #<Schedule id: 431, date: "2016-06-23", notes: "", price: "253", promo: "", status: "available", boat_id: 3, created_at: "2016-06-14 09:23:55", updated_at: "2016-06-14 09:23:55">]
and user inputs "from" and "to" dates. Lets say I have variables such
a = "2016-06-16".in_time_zone('UTC')
b = "2016-06-19".in_time_zone('UTC')
I would like to loop over Schedule table between these dates (a and b) and get the sum of prices..
I think of a such solution that, I can say;
a = "2016-06-16".in_time_zone('UTC')
b = "2016-06-19".in_time_zone('UTC')
schedules = Schedule.all
price = 0
dates = []
while a < b do
dates << a
a += 1.day
end
Then;
dates.each do |date|
schedules.each do |schedule|
if (date == schedule.in_time_zone('UTC'))
price += schedule.price.to_i
end
end
end
but do not know if that is the most convenient way to do.
Why not taking the advantage of DB native implementations. You can do it in SQL.
date_from = "2016-06-16".in_time_zone('UTC')
date_to = "2016-06-19".in_time_zone('UTC')
Schedule
.where(date: date_from..date_to) # sql BETWEEN operator
.sum("price") # SQL aggregate function.

Join array and hash

Ruby on Rails 4
I am trying to join an Array of questions and a grouped by hash together by the question's id.
The Hash is grouped by the question_id attribute of its records from Answers.
The Array has all the Questions, and index is id.
I was trying to put them into an array, #pdf. The question first then the answers by the enumerator index. But it is behaving odd.
#pdf = []
#test = Test.find(params[:id])
#test_questions = #test.questions
answers = Answer.find(:all)
#all_answers = answers.group_by(&:question_id)
#test_questions.each do |q|
#pdf << q
#pdf << #all_answers.select { |i| i == q }
end
The log shows this:
=> [#<Question id: 1, content: "How did the chicken cross the road?", question_type: "MC", category: "ip_voice", product_id: 8, active: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14", user_id: 1>, {}, #<Question id: 2, content: "Is this working?", question_type: "TF", category: "ip_voice", product_id: 6, active: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53", user_id: 1>, {}]
This is #all_answers:
=> {1=>[#<Answer id: 1, content: "It walked", question_id: 1, correct: false, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">, #<Answer id: 2, content: "It was thrown", question_id: 1, correct: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">, #<Answer id: 3, content: "It got run over and pushed", question_id: 1, correct: false, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">], 2=>[#<Answer id: 4, content: "False", question_id: 2, correct: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53">, #<Answer id: 5, content: "True", question_id: 2, correct: false, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53">]}
This is #test_questions:
=> #<ActiveRecord::Associations::CollectionProxy [#<Question id: 1, content: "How did the chicken cross the road?", question_type: "MC", category: "ip_voice", product_id: 8, active: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14", user_id: 1>, #<Question id: 2, content: "Is this working?", question_type: "TF", category: "ip_voice", product_id: 6, active: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53", user_id: 1>]>
I am new to many Rails/Ruby methods.
I think this is the code you need:
#pdf = []
#test = Test.find(params[:id])
#test_questions = #test.questions
answers = Answer.find(:all)
#all_answers = answers.group_by(&:question_id)
#test_questions.each do |q|
#pdf << q
#pdf += #all_answers[q.id]
end
This should create something like:
=> [#<Question id: 1, content: "How did the chicken cross the road?", question_type: "MC", category: "ip_voice", product_id: 8, active: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14", user_id: 1>, #<Answer id: 1, content: "It walked", question_id: 1, correct: false, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">, #<Answer id: 2, content: "It was thrown", question_id: 1, correct: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">, #<Answer id: 3, content: "It got run over and pushed", question_id: 1, correct: false, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">,
#<Question id: 2, content: "Is this working?", question_type: "TF", category: "ip_voice", product_id: 6, active: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53", user_id: 1>, #<Answer id: 4, content: "False", question_id: 2, correct: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53">, #<Answer id: 5, content: "True", question_id: 2, correct: false, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53">]
What you probably want to do is to have something like this:
class Test < ActiveRecord::Base
has_many :questions
has_many :answers, :through => :questions
end
class Question < ActiveRecord::Base
belongs_to :test
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
end
And then do:
test = Test.find(params[:id]).joins(:questions, :answers)
This will fetch questions and answers in one query and you can do things like:
test.questions.first.answers
or
test.answers
and for the pdf:
test.questions.each do |q|
pdf = test.questions.collect do |q|
[q, q.answers]
end

how to select data from database based created_at today in rails

how to select data from database based created_at today in rails?
example :
[#<Event id: 1, customer_id: 1, therapist_id: 1, location_id: 1, service_id: 3, walkin: true, cancel: false, cancel_reason: nil, room_id: 5, starts_at: "2014-04-03 21:31:13", stops_at: nil, created_at: "2014-04-14 10:13:52", updated_at: "2014-04-14 10:13:52">, #<Event id: 2, customer_id: 2, therapist_id: 2, location_id: 2, service_id: 2, walkin: false, cancel: false, cancel_reason: nil, room_id: 1, starts_at: "2014-04-05 21:31:13", stops_at: nil, created_at: "2014-04-14 10:13:52", updated_at: "2014-04-14 10:13:52">, #<Event id: 3, customer_id: 1, therapist_id: 2, location_id: 1, service_id: 1, walkin: false, cancel: false, cancel_reason: nil, room_id: 5, starts_at: "2014-04-07 21:31:13", stops_at: nil, created_at: "2014-04-14 10:13:52", updated_at: "2014-04-14 10:13:52">, #<Event id: 4, customer_id: 2, therapist_id: 2, location_id: 2, service_id: 2, walkin: false, cancel: false, cancel_reason: nil, room_id: 1, starts_at: "2014-04-09 21:31:13", stops_at: nil, created_at: "2014-04-14 10:13:52", updated_at: "2014-04-14 10:13:52">, #<Event id: 5, customer_id: 14, therapist_id: 2, location_id: 2, service_id: 1, walkin: true, cancel: false, cancel_reason: "", room_id: 8, starts_at: "2014-04-15 06:47:00", stops_at: "2014-04-15 07:47:00", created_at: "2014-04-15 06:47:14", updated_at: "2014-04-15 06:47:14">]
and when i collect data based created_at today i get result :
<Event id: 5, customer_id: 14, therapist_id: 2, location_id: 2, service_id: 1, walkin: true, cancel: false, cancel_reason: "", room_id: 8, starts_at: "2014-04-15 06:47:00", stops_at: "2014-04-15 07:47:00", created_at: "2014-04-15 06:47:14", updated_at: "2014-04-15 06:47:14">
how to collect all data where data created_at just today in rails?
thanks before
Please try this:
Event.where("DATE(created_at) = DATE(?)", Time.now)
Please have a try with this code.
Event.where("created_at >= ? and created_at <= ?", Time.now.beginning_of_day, Time.now.end_of_day)
To fetch today's events, it will return only today's events
Event.where("created_at = ?", Date.today)
Here's what I have tried in my console
2.0.0p247 :008 > Article.where("created_at < ?", Date.today)
Article Load (0.5ms) SELECT `articles`.* FROM `articles` WHERE (created_at < '2014-04-15')
=> #<ActiveRecord::Relation [#<Article id: 2, title: "Villa Kerylos: A Greek Dream.. A Modern Villa", description: "An inside look at one of the Mediterranean's most i...", url: "http://frenchantiques.blogspot.com/2009/05/villa-ke...", is_open_in_new_window: true, created_at: "2013-12-26 07:03:17", updated_at: "2013-12-26 10:28:36">, #<Article id: 4, title: "Kenzo Auctions Personal Art Collection", description: "Kenzo Auctions Personal Art Collection", url: "http://frenchantiques.blogspot.com/2009/06/kenzo-au...", is_open_in_new_window: false, created_at: "2013-12-26 09:57:21", updated_at: "2013-12-26 09:57:21">]>
Event.where("created_at > ?" Time.now.to_date.to_time) should work, because you want todays entries. Also, a good Idea, is those of the last 24 hours, which should be Event.where("created_at > ?-60*60*24 and created_at < ?" Time.now)
Event.where('created_at >= ?', Date.today)
Maybe you can parse the created_at to the same short format and compare, but this should be enough.

couldnot maintain the string format that is needed

I want my result in this format
data: [{"label":"present","value":35},
{"label":"absent","value":50},
{"label":"leave","value":45},
{"label":"performance","value":67}]
I did try this code
data: <%= #orders.map { |d| {label: d.shipping, value: d.price}}.to_json.html_safe -%>
which gives result
data: [{"label":"present","value":"35"},
{"label":"absent","value":"50"},
{"label":"leave","value":"45"},
{"label":"performance","value":"67"}]
here problem is in the first label present i obtain value "35" in this format but i need value 35 only without "". How could i get this?
my data in #orders is
[#<Order id: 8, price: "35", purchased_at: "2012-01"
, shipping: "present", created_at: "2012-12-13 08:17:39",
updated_at: "2012-12-13 08:50:13">, #<Order id: 9, price
: "50", purchased_at: "2012-02", shipping: "absent", created_at
: "2012-12-13 08:31:24", updated_at: "2012-12-13 08:50:55">,
#<Order id: 12, price: "45", purchased_at: "2012-03", shipping:
"leave", created_at: "2012-12-13 08:48:37", updated_at: "2012-12-13 08:51:07">
, #<Order id: 13, price: "67", purchased_at: "2012-04", shipping:
"performance", created_at: "2012-12-13 08:48:47", updated_at: "2012-12-13 08:51:18">]
data: <%= #orders.map { |d| {label: d.shipping, value: d.price.to_i}}.to_json.html_safe -%>

Resources