Why escape_javascript printed as text in coffeescript? - ruby-on-rails-4

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'

Related

multiple render in rails controller action while calling an api

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

how to add two product in opencart?

How to add two products . For example I added product1 . I want to split that product1 into product with media and product1 without media. Quantity are same .
In the product list it has to show in two different entries . Below is the code for adding product. now it is taking only one ..
$this->data[$key] = array(
'key' => $key,
'product_id' => $product_query->row['product_id'],
'name' => $product_query->row['name'],
'model' => $product_query->row['model'],
'shipping' => $product_query->row['shipping'],
'image' => $product_query->row['image'],
'option' => $option_data,
'download' => $download_data,
'quantity' => $quantity,
'minimum' => $product_query->row['minimum'],
'subtract' => $product_query->row['subtract'],
'stock' => $stock,
'price' => ($price + $option_price),
'total' => ($price + $option_price) * $quantity,
'reward' => $reward * $quantity,
'points' => ($product_query->row['points'] ? ($product_query->row['points'] + $option_points) * $quantity : 0),
'tax_class_id' => $product_query->row['tax_class_id'],
'weight' => ($product_query->row['weight'] + $option_weight) * $quantity,
'weight_class_id' => $product_query->row['weight_class_id'],
'length' => $product_query->row['length'],
'width' => $product_query->row['width'],
'height' => $product_query->row['height'],
'length_class_id' => $product_query->row['length_class_id'],
'recurring' => $recurring
);

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]

Nested form params not working due to strong parameters

I have a model Declaration which has many Costs:
class Declaration < ActiveRecord::Base
has_many :costs
accepts_nested_attributes_for :costs
end
class Cost < ActiveRecord::Base
belongs_to :declaration
end
I want a form where I have 10 cost lines for a declaration, so in the Declaration controller I have the follwing, with the permit params for strong parameters:
def new
#declaration = Declaration.new
#costs = Array.new(10) { #declaration.costs.build }
end
def create
#declaration = Declaration.new(declaration_params)
if #declaration.save
redirect_to user_declarations_path, notice: I18n.t('.declaration.message_create')
else
render action: "new"
end
end
private
def declaration_params
params.require(:declaration).permit(:approval_date, :submit_date, :status, :user_id, :declaration_number,
costs_attributes: [:id, :description, :amount_foreign, :rate, :amount, :cost_date, :projectuser_id])
end
And there is the form of course, so when I submit the form I see this in the log:
Started POST "/users/3/declarations" for 127.0.0.1 at 2013-09-05 19:12:38 +0200
Processing by DeclarationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"mhaznOuBy/zj7LA/nIpDTy7X2u5UrR+0jleJsFid/JU=", "declaration"=>{"user_id"=>"3", "cost"=>{"cost_date(3i)"=>"", "cost_date(2i)"=>"", "cost_date(1i)"=>"", "projectuser_id"=>"", "description"=>"", "amount_foreign"=>"", "rate"=>"", "amount"=>""}}, "commit"=>"Opslaan", "user_id"=>"3"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id" ASC LIMIT 1
Unpermitted parameters: cost
So why do I get an unpermitted parameter cost??
Update: declaration form added below:
- if can? :create, Declaration
= form_for [current_user, #declaration] do |f|
= f.hidden_field :user_id, value: current_user.id
.row
.page-header
.span7
%h1.title
%i{ class: "icon-coffee icon-large" }
= I18n.t('.declaration.add_title')
.span5
.action
- if can? :create, Declaration
= link_to I18n.t('.general.cancel'), user_declarations_path(current_user), class: 'btn'
= f.submit(class: 'btn', value: I18n.t('.general.save'))
.row
.span12
= render "layouts/error_messages", target: #declaration
.row
.span12
= render "form", f: f
And the rendered form:
.row
.span12
%table.table.table-striped#declarations
%thead
%tr
%th= I18n.t('.cost.cost_date')
%th= I18n.t('.cost.project')
%th= I18n.t('.cost.description')
%th= I18n.t('.cost.amount_foreign')
%th= I18n.t('.cost.rate')
%th= I18n.t('.cost.amount')
%tbody
- #costs.each do |cost|
= f.fields_for cost, html: { class: "form-inline"} do |c|
%tr
%td{ "data-title" => "#{I18n.t('.cost.cost_date')}" }= c.date_select :cost_date, { include_blank: true, default: nil }
%td{ "data-title" => "#{I18n.t('.cost.project')}" }= c.collection_select :projectuser_id, #projectusers, :id, :full_name, include_blank: true
%td{ "data-title" => "#{I18n.t('.cost.description')}" }= c.text_field :description, class: "input-large"
%td{ "data-title" => "#{I18n.t('.cost.amount_foreign')}" }= c.text_field :amount_foreign, class: "input-small", type: :number, step: "any"
%td{ "data-title" => "#{I18n.t('.cost.rate')}" }= c.text_field :rate, class: "input-small", type: :number, step: "any"
%td{ "data-title" => "#{I18n.t('.cost.amount')}" }= c.text_field :amount, class: "input-small", type: :number, step: "any"
With permit! I get this error message:
Started POST "/users/3/declarations" for 127.0.0.1 at 2013-09-09 09:29:44 +0200
Processing by DeclarationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jQwy7psQwixneWF8DezrR/Wo5VKU/dpfz+sosiatm9c=", "declaration"=>{"user_id"=>"3", "cost"=>{"cost_date(3i)"=>"", "cost_date(2i)"=>"", "cost_date(1i)"=>"", "projectuser_id"=>"", "description"=>"", "amount_foreign"=>"", "rate"=>"", "amount"=>""}}, "commit"=>"Opslaan", "user_id"=>"3"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id" ASC LIMIT 1
Completed 500 Internal Server Error in 6ms
ArgumentError - wrong number of arguments (6 for 0):
app/controllers/declarations_controller.rb:70:in `declaration_params'
app/controllers/declarations_controller.rb:21:in `create'
First impression is you are returning three cost_date parameters. I think this needs to be returned as an array. Your params would then be:
def declaration_params
params.require(:declaration).permit(:approval_date, :submit_date, :status, :user_id, :declaration_number,
costs_attributes: [:id, :description, :amount_foreign, :rate, :amount, :projectuser_id, :cost_date =>[]])
end
Then instead of your web server getting back:
... "cost"=>{"cost_date(3i)"=>"", "cost_date(2i)"=>"", "cost_date(1i)"=>"",...
it should get:
"cost"=>{"cost_date"=>["","",""],...
though without seeing the form I don't know if this is what you are trying to achieve.
It seems that changing this:
- #costs.each do |cost|
= f.fields_for cost, html: { class: "form-inline"} do |c|
to this:
= f.fields_for(:costs) do |c|
Does the trick, because now all costs records are being saved. In the controller I have now this:
#declaration = Declaration.new
10.times do |n|
#declaration.costs.build
end
The only issue I have now left is that it saves empty cost records.

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
}
})