I have a strange problem, i can't even get the source of it.
I'm using ajax GET request to a specified url, that routes to :controller => pages, :action => make_affiche_link, there i have the following:
#album = Album.find( params[:album_id] )
#upd = { :affiche_id => params[:affiche_id] }
if #album.update_attributes( #upd )
#out = {:key => '1', :message => "success"}
render :json, #out.to_json
else
#out = {:key => '0', :message => "something bad is going here..."}
render :json => #out.to_json
end
and what i get is this:
index 49793 out of string
And i have both :affiche_id and :album_id in params properly
Thank you for any help!
It is Json #out = {:key => '1', :message => "success"}, you try convert Json to Json #out.to_json. Use render :json, #out
Related
I am using recycled code from a project but in this version I am not having good results.
I use Rails 5.2.2 and RVM Ruby 2.7.1
I need to use this function to call an ajax and deliver the already stored data of a client and fill out a form, the data will be searched through the RUN of each client
I don't understand why the match () are not working for me
Controller Pacientes
class Ajax::PacientesController < ApplicationController
layout nil
def obtener_datos_paciente
#usuario = params[:rut]
usuario = Usuario.first :rut => params[:rut]
puts usuario.inspect.yellow
if usuario.nil?
render :json => {
:exito => true,
:mensaje => "No existen registros asociados al rut #{params[:rut]}."
}
else
render :json => {
:exito => true,
:es_empresa => true,
:mensaje => "El paciente con rut #{params[:rut]} ya existe.",
:data => {
:id => usuario.id,
:rut => usuario.rut,
:primer_nombre => usuario.primer_nombre,
:segundo_nombre => usuario.segundo_nombre,
:apellido_paterno => usuario.apellido_paterno,
:apellido_materno => usuario.apellido_materno,
:direccion => usuario.direccion,
:ciudad => usuario.ciudad,
:comuna => usuario.comuna,
:telefono => usuario.telefono,
:email => usuario.email
}
}
end
rescue Excepciones::DatosNoExistentesError => e
flash.now[:info] = e.message
render :json => { :mensaje => e.message }
end
end
Routes
match(
"ajax/pacientes/:rut" => "ajax::pacientes#obtener_datos_paciente",
:as => :obtener_datos_paciente,
:via => :get
)
Controller Usuario
require 'json'
class UsuariosController < ApplicationController
helper_method :url_paciente
def index
#usuarios = Usuario.all
end
def ingreso_paciente
end
def registrar_ingreso
end
def ingresar_ficha_kinesica
alias url_paciente obtener_datos_paciente_ajax_pacientes_path
end
end
The easiest fix would be to rename your controller to:
class PacientesController < ApplicationController and match to "ajax/pacientes/:rut" => "pacientes#obtener_datos_paciente"
If your controller must exist in the Ajax namespace, then it should probably have a namespaced route as well. An example can be found in this answer.
I' am trying to create a simple wrapper for skyscanner API. The problems is that when try to get the sessionKey, what I get is <HTTParty::Response:0x10 parsed_response=nil, #response=#<Net::HTTPUnsupportedMediaType 415 Unsupported Media Type readbody=true>. I am not sure what is that I am doing wrong. I am new to rails and I will appreciate any direction on how to solve this problem?. Thanks
require 'httparty'
class Skyscanner
include HTTParty
format :json
base_uri "http://partners.api.skyscanner.net/apiservices/pricing"
def self.find(originplace, destinationplace)
#options = { query:
{
:apiKey => "API_KEY",
:country => "US",
:currency => "USD",
:locale => "en-us",
:adults => 1,
:children => 0,
:infants => 0,
:originplace => originplacea,
:destinationplace => destinationplace,
:outbounddate => "2017-02-20",
:inbounddate => "2017-02-27",
:locationschema => "iata",
:cabinclass => "Economy"
}
}
#headers = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'}
#sessionkey_request = HTTParty.post("http://partners.api.skyscanner.net/apiservices/pricing/v1.0/",:body => #options,:headers => #headers)
puts #sessionkey_request.inspect
#get_sessionkey = #sessionkey_request.headers['location']
#sessionkey = #get_sessionkey.to_s().split('/').last
puts #sessionkey.inspect
end
end
If anyone have a better way of approaching this wrapper, please advice me on how to. Thanks
This is what I have:
def index
#attachments = current_user.attachments.all
respond_to do |format|
format.json do
render :json => #attachments.map { |o| { url: o.picture.thumb.url }}
end
end
end
=> [{:url=>"/uploads/attachment/picture/7/thumb_df3c0c3c.jpg"}, {:url=>"/uploads/attachment/picture/12/thumb_dd7839ee.jpg"}, ... }]
How can I change the key from :url to :thumb?
=> [{:thumb=>"/uploads/attachment/picture/7/thumb_df3c0c3c.jpg"},
{:thumb=>"/uploads/attachment/picture/12/thumb_dd7839ee.jpg"}, ... }]
This is the whole object after: render :json => #attachments
My goal: thumb: thumb: "/uploads/attach..."
Background: https://www.froala.com/wysiwyg-editor/docs/concepts/image-manager
I use the gem carrierwave to create a thumb
response.map! { |urls| { :thumb => urls[:url] } }
change key from "url" to "thumb"
render :json => #attachments.map { |o| { **thumb: o.picture.thumb.url** }}
I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.
I am trying to parse XML using rexml Xpath, but facing error as const_missing: XPath in rhomobile application. can anyone give me the solution.
Below is the sample code:
file = File.new(file_name)
begin
require 'rexml/document'
xmldoc = REXML::Document.new(file)
names = XPath.match(xmldoc, "//MP_HOST_NAME" )
in your build.yml file:
extensions:
- rexml
if using blackberry, replace rexml with rhoxml
Assuming you've done this, replace your XPath with:
REXML::XPath.match(xmldoc, "//MP_HOST_NAME" )
Here is a sample controller I knocked to test xml parsing
I can use the get_names method in the view then to get an array of names
require 'rho/rhocontroller'
require 'rexml/document'
class WebServiceTestController < Rho::RhoController
def index
##get_result = ""
Rho::AsyncHttp.get(
:url => 'http://www.somesite.com/some_names.xml',
#:authorization => {:type => :basic, :username => 'user', :password => 'none'},
:callback => (url_for :action => :httpget_callback),
:authentication => {
:type => :basic,
:username => "xxxx",
:password => "xxxx"
},
:callback_param => "" )
render :action => :wait
end
def get_res
##get_result
end
def get_error
##error_params
end
def httpget_callback
if #params["status"] != "ok"
##error_params = #params
WebView.navigate( url_for(:action => :show_error) )
else
##get_result = #params["body"]
begin
# require "rexml/document"
##doc = REXML::Document.new(##get_result)
# puts "doc : #{doc}"
rescue Exception => e
# puts "Error: #{e}"
##get_result = "Error: #{e}"
end
WebView.navigate( url_for(:action => :show_result) )
end
end
def show_error
render :action => :error, :back => '/app'
end
def show_result
render :action => :index, :back => "/app"
end
def get_doc
##doc
end
def get_names
names = []
REXML::XPath.each( get_doc, "//name_or_whatever_you_are_looking_for") do |element|
names << element.text
end
names
end
end
ensure that rhoxml is set in the build.yml file rather than rexml this works fine and it's a little faster