multiple render in rails controller action while calling an api - ruby-on-rails-4

I want that my rails controller index action to render multiple output at once , my controller:
class Api::V1::Ola::OlaBookingsController < ApplicationController
def index
lat = params[:lat].to_s
long = params[:long].to_s
drop_lat = params[:drop_lat].to_s
drop_lng = params[:drop_lng].to_s
ola_query = {
"pickup_lat" => lat,
"pickup_lng" => long,
"drop_lat" => drop_lat ,
"drop_lng" => drop_lng
}
ola_body = {
"pickup_lat" => lat,
"pickup_lng" => long,
"drop_lat" => drop_lat,
"drop_lng" => drop_lng,
"pickup_mode" => "NOW",
"category" => "auto"
}
ola_headers = {
"Authorization" => "Bearer ",
"X-APP-TOKEN" => ""
}
#ola_products = HTTParty.get(
"http://sandbox-t.olacabs.com/v1/products",
:query => ola_query,
:headers => ola_headers
).parsed_response
#ola_booking = HTTParty.post(
"http://sandbox-t.olacabs.com/v1/bookings/create ",
:body => ola_body,
:headers => ola_headers
).parsed_response
render :json => #ola_booking
render :json => #ola_products
end
end
I want both responses to be coming on controller without generating a viw.
But it gives error "multiple render not possible" , how to fix it?

You can not have 2 renders what you can do is combine the 2 objects one after the other like
render :json => #ola_booking.to_json + #ola_products.to_json
you should try it out and let me know how it worked

you can try this.
respond_to do |format|
format.json { render :json => {:ola_booking => #ola_booking,
:ola_products => #ola_products }}
end

Related

Set values for default address fields in Drupal 8

I need to set values for default address fields(langcode, country_code, administrative_area, address_locality ect.) when I create a node. I used below code in the submitForm function of a Form class which is extends by Drupal\Core\Form\FormBase class. But it not works for me.
$venueNode = Node::create([
'type' => 'venue',
'title' => 'Venue',
'field_address' => [
'country_code' => 'US',
'address_line1' => '1098 Alta Ave',
'locality' => 'Mountain View',
'administrative_area' => 'US-CA',
'postal_code' => '94043',
],
]);
$venueNode->save();
I made a mistake here. There should be a 0 index for field_address. Therefore the code should be like below.
$venueNode = Node::create([
'type' => 'venue',
'title' => 'Venue',
'field_address' => [
0 => [
'country_code' => 'US',
'address_line1' => '1098 Alta Ave',
'locality' => 'Mountain View',
'administrative_area' => 'US-CA',
'postal_code' => '94043',
],
],
]);
$venueNode->save();

Rails sort association proxy after new object is build

I have two models,
class User < ActiveRecord::Base
has_many :posts, -> { order('post.id') }
end
class Post < ActiveRecord::Base
belongs_to: user
end
For instance i'm having a #user and two posts associated. while doing #user.posts, the result be like.
[
[0] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[1] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
Now, I'm building one more extra object by doing #user.posts.build and
that the below result of doing #user.posts
[
[0] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[1] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
},
[2] #<Post:0x0000000aa53a50> {
:id => nil,
:title => nil,
:comment => nil
},
]
What i actually want is, to sort by object with nil first. The result should exactly look like,
[
[0] #<Post:0x0000000aa53a50> {
:id => nil,
:title => nil,
:comment => nil
},
[1] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[2] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
It can also be done by an custom method to sort by looping through each object. But don't want to write another method. The result should in Association Proxy and not an Array
Is it possible to achieve it in association proxy itself?
Suppose, you have the #posts variable where it contains the nil item.
#posts.sort{|i,j| i.id && j.id ? i <=> j : j.id ? -1 : 1 }
result => [nil, 3, 5]

Why escape_javascript printed as text in coffeescript?

My goal is to render a partial view after delete using Ajax to regenerate a table and its pagination. But when I try to do this in my schedules.js.coffee:
$(".delete_schedule").bind "ajax:success", ->
$(this).closest('tr').fadeOut "slow", ->
$("table tr.numbered_row:visible").each (i) ->
$(this).children(".seq").text i + 1
$("#schedules").html('#{ escape_javascript render("schedules")}')
$("#paginator").html('#{ escape_javascript(paginate(#schedules, :remote => true).to_s)}')
the page source of the output is like:
<tbody id="schedules">#{ escape_javascript render(:partial => "schedules")}</tbody>
<div id="paginator">#{ escape_javascript(paginate(#schedules, :remote => true).to_s)}</div>
I wonder why the escape_javascript printed as text instead of run as a command? My suspect was because of there is " inside the $("#schedules").html('#{ escape_javascript render("schedules")}'), but I have to use the " inside my code.
Thanks!
I am using Rails 4, HAML, Coffeescript and Kaminari.
Below is the code of my controller for delete:
schedules_controller.rb
def destroy
#schedule = Schedule.find(params[:id])
#location = Location.find(#schedule.location_id)
#schedules = Schedule.where(:doctor_id => current_doctor.id,
:location_id => params[:location_id] ).order(days_id: :asc).page(params[:page]).per(5)
respond_to do |format|
if #schedule.destroy
format.json { head :no_content, status: :ok }
end
end
end
my main view:
index.html.haml
%h2 Your schedules
- #i = 0
.table-responsive
%table.table.table-striped{:id => "schedules_table"}
%thead
%tr
%th No
%th Day
%th Start
%th End
%th Away?
%th Action
%tbody{:id => "schedules"}
= render :partial => 'schedules'
%br/
%div{:id => "paginator"}
= paginate #schedules, :remote => true
%br/
= link_to 'New Schedule', new_location_schedule_path
|
\#{link_to 'Back', doctor_locations_path(current_doctor)}
And my partial view:
_schedules.html.haml
- #schedules.each_with_index do |schedule, i|
%tr.numbered_row
%td.seq= i + 1
%td
= schedule.find_day_name()
%td= schedule.start_time.strftime("%H:%M")
%td= schedule.end_time.strftime("%H:%M")
%td{:id => "#{schedule.id}"}
%a.status_link.btn.btn-danger.btn-sm{"data-href" => set_schedule_status_path(location_id: params[:location_id], id: schedule.id), :style => "#{schedule.is_away ? '' : 'display: none'}", :id => "#{schedule.id}"}
%i.fa.fa-times
%span Away
%a.status_link.btn.btn-success.btn-sm{"data-href" => set_schedule_status_path(location_id: params[:location_id] ,id: schedule.id), :style => "#{schedule.is_away ? 'display: none' : '' }", :id => "#{schedule.id}"}
%i.fa.fa-check-square-o
%span Available
%td
- concat link_to icon('pencil'), edit_schedule_path(schedule, location_id: params[:location_id])
- concat " | "
- concat link_to icon('remove'), [#location, schedule], method: :delete, remote: :true, data: { confirm: 'Are you sure?' }, :class => 'delete_schedule'

Kendo UI Grid Row Template

I had a problem on how to apply row Template data binding into it. I not sure what is the syntax to do so. I am using server binding mode. Below is my code
#(Html.Kendo().Grid((IEnumerable<IcmsViewModel.LookupView>)ViewData["LookupView"]) // Bind the grid to the Model property of the view
.Name("Grid")
.CellAction(cell =>
{
if (cell.DataItem.Active == false)
{
cell.HtmlAttributes["style"] = "background-color: red";
}
}
)
.Columns(columns =>
{
columns.Bound(p => p.LookupValue).ClientTemplate(" ").Title("Short Name").Width(300);
columns.Bound(p => p.Description).Width(300);
columns.Bound(p => p.Active).Width(300);
columns.Command(command => { command.Edit(); command.Destroy(); });
})
**.RowTemplate(rows =>
"<tr><td>Testing</td>" +
"<td colspan=\"2\"><input type=\"button\" name=\"ClickMe\" value=\"ClickMe\" onclick=\"javascript:window.open(('/Test/ViewTest'), 'ViewTest', 'height=' + (window.screen.height - 100) + ',width=200,left=' + (window.screen.width - 250) + ',top=10,status=no,toolbar=no,resizable=yes,scrollbars=yes');\"/></td>" +
"<td>Name</td></tr>"
)**
.ToolBar(commands => commands.Create())
.Groupable()
.Pageable()
.Sortable()
//.Filterable()
.Scrollable(x => x.Height(600))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Server()
.Model(model => { model.Id(p => p.Id); model.Field(p => p.Id).Editable(false); })
.Create(create => create.Action("CreateLookup", "Icms"))
.Read(read => read.Action("Lookup", "Icms"))
.Update(update => update.Action("UpdateLookup", "Icms"))
.Destroy(destroy => destroy.Action("Destroy", "Sample"))
)
)
Currently I hard code the value in the row template, how can I bind it with the data in database, if i want to apply the row template.
Example
.RowTemplate(rows =>
"p.LookupValue" +
"" +
"p.Description"
)
Please help me on this as I am new to kendo UI. Thanks a lot.
Why don't you use Template on the column definition :
.Columns(columns =>
{
columns.Bound(p => p.LookupValue)
.Template(#<text>#item.LookupValue #item.Description</text>).Title("Short Name").Width(300);
columns.Bound(p => p.Active).Width(300);
columns.Command(command => { command.Edit(); command.Destroy(); });
})

Update payment details using Authorize.net

When I update the existing subscription info using update_recurring method of autorize.net gateway then payment details (credit card number, CVV number and expiry date) are not being updated.
My code snippet is as follows:-
def create_card_subscription
credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => params[:payment_details][:name],
:last_name => params[:payment_details][:last_name],
:number => params[:payment_details][:credit_card_number],
:month => params[:expiry_date_month],
:year => params[:expiry_date_year],
:verification_value => params[:payment_details][:cvv_code]
)
if credit_card.valid?
gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new(:login => '*********', :password => '**************')
response = gateway.update_recurring(
{
"subscription.payment.credit_card.card_number" => "4111111111111111",
:duration =>{:start_date=>'2010-04-21', :occurrences=>1},
:billing_address=>{:first_name=>'xyz', :last_name=>'xyz'},
:subscription_id=>"******"
}
)
if response.success?
puts response.params.inspect
puts "Successfully charged $#{sprintf("%.2f", amount / 100)} to the credit card #{credit_card.display_number}. The Account number is #{response.params['rbAccountId']}"
else
puts response.message
end
else
#Credit Card information is invalid
end
render :action=>"card_payment"
end
Try something like this:
credit_card = ActiveMerchant::Billing::CreditCard.new({
:number => self.ccnum,
:verification_value => self.ccv,
:month => self.exp_month,
:year => self.exp_year,
:first_name => self.first_name,
:last_name => self.last_name
})
response = gateway.update_recurring({
:subscription_id => self.subscription_id,
:amount => 10000000,
:credit_card => credit_card,
:customer => {
:email => "fjdksl#jklfdsjflkd.com"
},
:billing_address => {
:first_name => self.first_name,
:last_name => self.last_name,
:address1 => self.address + " " + self.address2,
:city => self.city,
:state => self.state,
:country => "US",
:zip => self.zip
}
})