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]
Related
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();
using this Hash object
{"foo" => {"bar" => 1, "baz" => 2}, "bla" => [1,2,3]}
I want to produce this array of Hash objects
[
{"foo" => "*", "bla" => [1,2,3]},
{"foo" => {"bar" => "*", "baz" => 2}, "bla" => [1,2,3]},
{"foo" => {"bar" => "1", "baz" => "*"}, "bla" => [1,2,3]},
{"foo" => {"bar" => "*", "baz" => 2}, "bla" => "*"},
]
Where I basically went over each key and changed its value to "*" while preserving the overall structure of the hash and saved the new hash produced in some array.
I have tried many ideas, but most just wont work as I can guess the Array type before, I only know this hash is produced by JSON.parse and then changed into Hash(String, JSON::Any)
My current try at it
hash = {"bar" => {"and" => "2", "br" => "1"}}
arr = [hash, {"bar" => "1"}]
arr.delete(arr.last)
arr.delete(hash)
def changer(hash, arr, original = nil)
original = hash.dup
hash.each do |k, v|
if v.is_a?(Hash)
changer(v, arr, hash)
elsif v.is_a?(Array)
v.each do |a|
if a.is_a?(Hash)
changer(a, arr, hash)
end
end
elsif v.is_a?(String) && original.is_a?(Hash(String, String))
original[k.to_s] = "*"
arr << original
end
end
end
Crystal v0.25.0 implements JSON::Any and YAML::Any without recursive aliases. With that change:
require "json"
hash = JSON.parse(%(
{"foo": {"bar": 1, "baz": 2}, "bla": [1,2,3]}
))
def changer(any : JSON::Any)
result = [JSON::Any.new("*")]
if (hash = any.as_h?)
hash.each do |key, value|
changer(value).each do |s|
result << JSON::Any.new(hash.merge({key => s}))
end
end
end
result
end
puts changer(hash).join("\n")
*
{"foo" => "*", "bla" => [1_i64, 2_i64, 3_i64]}
{"foo" => {"bar" => "*", "baz" => 2_i64}, "bla" => [1_i64, 2_i64, 3_i64]}
{"foo" => {"bar" => 1_i64, "baz" => "*"}, "bla" => [1_i64, 2_i64, 3_i64]}
{"foo" => {"bar" => 1_i64, "baz" => 2_i64}, "bla" => "*"}
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
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'
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
}
})