How to transform an object into an array from REST POST output - ruby-on-rails

I am building an Rails 5 app.
In this app I create a user with customfields. The output I get from the client (Javascript) is a bit wrong (and I have no idea how to change that). How can I "transform" the output I get into the output I must have?
The below is what I get
"user_customfields_attributes" => {
"1533038627616" => {
"customfield_id" => "1", "value" => "test 1"
}, "1533038627617" => {
"customfield_id" => "2", "value" => "test 2"
}
}
The below is what I need
"user_customfields_attributes" => [{
"customfield_id" => 1,
"value" => "test 1"
}, {
"customfield_id" => 2,
"value" => "test 2"
}]
Thankful for all help!

Related

How to post nested JSON to HTTParty in Ruby on Rails

I am trying to work out the correct way to post a nested JSON object to an API using HTTParty.
I am getting a successful response using Postman to test the call:
POST: http://service.net/api
Headers: x-api-key : apikey123
Body :
{
"VehicleRequests": [{
"Id": "Vehicle1",
"Parameters": {
"Term": 60,
"CashDeposit": 10,
"DepositType": "Percentage",
"AnnualMileage": 10000
},
"PhysicalVehicle": {
"ExternalVehicleId": "12345",
"Type": "Car",
"Status": "PreOwned",
"OnTheRoadPrice": "30000",
"Mileage": "12345",
"Registration": {
"RegistrationNumber": "REGN0",
"DateRegisteredWithDvla": "01/01/2018"
}
}
}]
}
This returns:
{
"Vehicles": [
{
"Id": "Vehicle1",
"HasError": false,
"Error": null,
"FinanceQuotations": [
{
"HasError": false,
"Error": null,
"Finance": {
"Key": "HP",
"Notifications": [],
"Quote": {
.....
}
}
}
}
]
}
But i'm struggling to replicate the call from my rails app. I have a class set up which i'm calling on create
class Monthlyprice
def initialize()
#response = HTTParty.post('http://service.net/api',
:body =>{
:VehicleRequests=> [{
:Id => "Vehicle1",
:Parameters => {
:Term => 60,
:CashDeposit => 10,
:DepositType => "Percentage",
:AnnualMileage => 10000
},
:PhysicalVehicle => {
:ExternalVehicleId => "12345",
:Type => "Car",
:Status => "PreOwned",
:OnTheRoadPrice => "30000",
:Mileage => "12345",
:Registration => {
:RegistrationNumber => "REGN0",
:DateRegisteredWithDvla => "01/01/2018"
}
}
}].to_json
},
:headers => {"x-api-key" => "apikey123"})
puts(#response)
end
end
But this is returning the following error message from the API:
{"Error"=>{"UserMessage"=>"Request is invalid.", "TechnicalMessage"=>"Request Validation failed. Request had 2 error(s). 1: request.VehicleRequests[0].Id - The Id field is required.\r\n2: request.VehicleRequests[0].Parameters - The Parameters field is required.", "Code"=>"80000"}}
This is the same error that I get from the api in postman if I remove the Id and Parameters objects which suggests the contents of my VehicleRequests object is formatted incorrectly? Any advice would be great!
Can you please change the syntax like below :-
:body => {
}.to_json
that means you have to use .to_json where the body parenthesis close I think it's only syntax error.
Syntax :-
response = HTTParty.post("your request URL",
headers: {
.....
#your header content
.....
},
body: {
......
#your body content
.....
}.to_json
)
I have just edited in your code please try below code :-
#response = HTTParty.post('http://service.net/api',
:headers => {"x-api-key" => "apikey123"},
:body =>{
:VehicleRequests=> [{
:Id => "Vehicle1",
:Parameters => {
:Term => 60,
:CashDeposit => 10,
:DepositType => "Percentage",
:AnnualMileage => 10000
},
:PhysicalVehicle => {
:ExternalVehicleId => "12345",
:Type => "Car",
:Status => "PreOwned",
:OnTheRoadPrice => "30000",
:Mileage => "12345",
:Registration => {
:RegistrationNumber => "REGN0",
:DateRegisteredWithDvla => "01/01/2018"
}
}
}]
}.to_json
)
Hope this will help you :)

MongoDB Aggregation push zero in keys while doing group

I am not sure that this is a valid question or not. I have started working on mongodb aggregation. I have to make a graph for the data on daily, weekly, monthly basis.
I am using "$dayOfMonth", "$week", "$month" to group by depending on the date provided. ex if from and to dates difference is less or equal to 6 I am grouping on daily basis using "$dayOfMonth",
If from and to dates difference is greater than 6 and less than 30 grouping is done of "$week" and if differece is greater than 30 then grouping is done on monthly basis "$month".
I am passing date in my "$match". Is it possible to push 0 as keys if the gouping is not present.
example - from_date = "01/01/2018" to_date = "30/6/2018"
so grouping will be done on month. and suppose if I dont have date for 3 and 4th & 5th month. I want to push 0 in the nested keys as the value.
output = [
{"_id": "01/01/2018", "counter":12},
{"_id": "01/02/2018", "counter": 15},
{"_id":"01/06/2018", counter: 10}
]
expected_output =
[
{"_id": "01/01/2018", "counter":12},
{"_id": "01/02/2018", "counter": 15},
{"_id":"01/03/2018", counter: 0},
{"_id":"01/04/2018", counter:0},
{"_id":"01/05/2018", counter: 0},
{"_id":"01/06/2018", counter: 10}
]
I am using Rails and Mongoid Gem.
Query That I am using
converted = Analytics::Conversion::PharmacyPrescription.collection.aggregate([
{ "$match" => {
"organisation_id" => org_id.to_s,
"date" => {
"$gte" => from_date,
"$lte" => to_date
},
"role_ids" => {"$in" => [role_id, "$role_ids"]}
}
},{
"$project" => {
"total_count" => 1,
"converted_count" => 1,
"not_converted_count" => 1,
"total_invoice_amount" => 1,
"user_id" => 1,
"facility_id" => 1,
"organisation_id" => 1,
"date" => 1,
}
},{
"$group" => {
"_id" => { "#{groupby}" => "$date" },
"total_count" => {"$sum" => "$total_count"},
"converted_count" => { "$sum" => "$converted_count" },
"not_converted_count" => { "$sum" => "$not_converted_count"},
}
}
]).to_a
The Aggregation Framework can only aggregate the documents you have. You are actually asking it to add groups for documents that do not exist, but it has no way to "know" which groups to add.
What I would do is run the query as you have it, and afterwards "spread" the date units according to the chosen granularity (in your example it will be 01/01/2018, 01/02/2018, 01/03/2018, 01/04/2018, 01/05/2018, 01/06/2018, and run a simple function which will add an entry for each missing unit.

Attempted to handle event `loadedData` on while in state rootState.loaded.updated.uncommitted. Called with undefined

I am using ember-data to fetch json response from server side, my embeer model looks like.
App.Field = DS.Model.extend
component: DS.attr 'string'
fieldinfos: DS.hasMany('App.Fieldinfo')
App.Field.reopenClass
forInstitution: (institution)->
App.Field.find { institution_id: institution.id }
and my json response looks like
{
:login_fields => [
[0] {
:component => "ns4:FieldInfoComponent",
:id => 1,
:fieldinfo_ids => [
[0] 1
]
},
[1] {
:component => "ns4:FieldInfoComponent",
:id => 2,
:fieldinfo_ids => [
[0] 2
]
},
[2] {
:component => "ns4:FieldInfoComponent",
:id => 3,
:fieldinfo_ids => [
[0] 3
]
}
],
:fieldinfos => [
[0] {
:field_info_obj => "FieldInfoSingle",
:login_field_id => 1,
:id => 1,
:element_ids => [
[0] 1
]
},
[1] {
:field_info_obj => "FieldInfoSingle",
:login_field_id => 2,
:id => 2,
:element_ids => [
[0] 2
]
},
[2] {
:field_info_obj => "FieldInfoSingle",
:login_field_id => 3,
:id => 3,
:element_ids => [
[0] 3
]
}
]
}
it works perfectly when I call once
App.Field.find { institution_id: 1 }
but in between if I again call for different institution
App.Field.find { institution_id: 2 }
Following is the code that fetch loginfields whenever institution changes
loginFields: (->
return [] unless #get('institution')?
App.LoginField.forInstitution(#get 'institution')
).property 'institution'
It gives me Attempted to handle event loadedData on while in state rootState.loaded.updated.uncommitted. Called with undefined error
what I am doing wrong over here and what I need to do to resolve this error. help!

Google Analytics Referral - Ruby

I am using ruby, and attempting to get referrals from google analytics api. Here is what I have set up:
sa_referral = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + saprofileID,
'dimensions' => "ga:fullreferrer",
'metrics' => "ga:users",
'sort' => "-ga:users",
'filters' => "ga:source!=(direct);",
'start-date' => startDate,
'end-date' => endDate,
})
sa_referral_data = sa_referral do |row|
row = {
:referral => row['0'],
:members => row['1'],
}
end
send_event('sa_top_referrals', current: sa_referral_data)
This returns no data when called in the widget using sa_top_referrals. Below is the data the API is returning.
"columnHeaders": [
{
"name": "ga:fullreferrer",
"columnType": "DIMENSION",
"dataType": "STRING"
},
{
"name": "ga:users",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"totalsForAllResults": {
"ga:users": "35638"
},
"rows": [
[
"m.facebook.com/",
"1009"
],
[
"baidu",
"912"
],
[
"usasexguide.info/forum/showthread.php",
"613"
],
Ideally the information I am looking to pull down is the URL ex: m.facebook.com/ and the user count or "613". Those are the two items I am looking to pull. My question is how do I know what row those are equal to. Above i'm sending it using: :referral => row['0'], I'd assume the issue is that its not actually row 0, is there a way I can confirm this?
This should do it:
sa_referral_data = sa_referral['rows'] do |row|
rows.map{|r| { referrals:r[0], members:r[1] }}
end

How can i add parameter in mandrill html text?

Is there any way to include the parameter i html portion of mandrill ?
I am not using template.
here is my code.
$mandrill = new Mandrill('YOUR_API_KEY');
$message = array(
'html' => '<p>here is my email</p>',
'text' => 'Example text content',
'subject' => 'example subject',
'from_email' => 'message.from_email#example.com',
'from_name' => 'Example Name',
'to' => array(
array(
'email' => 'recipient.email#example.com',
'name' => 'Recipient Name',
'type' => 'to'
),
array(
'email' => 'recipient.email#example.com',
'name' => 'Recipient Name',
'type' => 'to'
)
),
What i want to do is to add a parameter to the html content.
'html' => '<p>here is my email{ param}</p>', // this line
How can i do this ?
Thanks
Sounds like you're looking to use Mandrill merge tags.
You can insert merge tags into your HTML content and have it inject personalized information for each recipient. They can be used in your content with the format *|MERGETAG|* and by defining "merge_vars" in your message array.
Here's an example from their docs:
"message": {
"global_merge_vars": [
{
"name": "var1",
"content": "Global Value 1"
}
],
"merge_vars": [
{
"rcpt": "emailadress#domain.com",
"vars": [
{
"name": "fname",
"content": "John"
},
{
"name": "lname",
"content": "Smith"
}
]
}
],
source:
http://help.mandrill.com/entries/21678522-How-do-I-use-merge-tags-to-add-dynamic-content-
In testing a bit, Mandrill actually supports a few merge tags "out of the box", so you should just be able to add *|EMAIL|* into your HTML content and it'll pull that email address in from your TO array.

Resources