Encode string params in rails api - ruby-on-rails

In this when I am passing phone as string in params rails api, it is being passed in the form of "\"9650661678\"". How to use escape string or how to encode it so that only string can be entered as input.
Any help will be welcomed ! Thanks in advance.
clients_controller.rb
def myzenica
mobile = params[:phone]
client = Client.where(:phone => mobile)
render :json => client
end
terminal
Started GET "/clients/myzenica?phone=%229650661678%22" for 127.0.0.1 at 2016-03-15 11:21:23 +0530
Processing by ClientsController#myzenica as */*
Parameters: {"phone"=>"\"9650661678\"", "client"=>{}}
Client Load (0.3ms) SELECT `clients`.* FROM `clients` WHERE `clients`.`phone` = '\"9650661678\"'
Completed 200 OK in 2ms (Views: 0.7ms | ActiveRecord: 1.2ms)

You can use CGI.
require 'cgi'
CGI.escape('%229650661678%22')
=> "\"9650661678\""
UPDATE:
def myzenica
require 'cgi'
mobile = CGI.escape(params[:phone])
client = Client.where(:phone => mobile)
render :json => client
end
NOTE:
In your input field which is on postman on your side. You should enter a text without double/single qoutes. Because postman field is just like input field on html tags. It will treat it all as string.

Related

"undefined method []" when parsing reddit api

I'm trying to request the json pages for multiple subreddits and take the title and link from each page for a college project. here's the code in question:
require 'rufus-scheduler'
require 'json'
require 'httparty'
ENV['TZ'] = 'Europe/Dublin'
scheduler = Rufus::Scheduler::singleton
scheduler.every '12h00m', :first_at => Time.now + 10 do
array_of_subreddits = ["pics", "memes", "funny", "aww", "memes",
"birdswitharms"]
array_of_subreddits.each do |category|
sleep 10 #wait 10 seconds between each request
#response = JSON.parse(HTTParty.get("http://reddit.com/r/#{category}/.json?limit=25").body)
#response['data']['children'].each do |data|
#link = data['data']['url']
#title = data['data']['title']
#category = category
Pic.create([{:title => "#{#title}", :link => "#{#link}", :category => "#{#category}"}])
end
end
end
this works perfectly sometimes, it will run through each one and end as it should. more often than not however it will give me this message after after one or two passes:
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/home_controller.rb:17:in `block in index'
app/controllers/home_controller.rb:9:in `each'
app/controllers/home_controller.rb:9:in `index'
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.8ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.2ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.2ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (66.2ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.4ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.5ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (51.6ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.3ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.5ms)
Rendered /Users/conorbreen/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (124.8ms)
Creating client classes is a much better way to work with httparty:
class RedditClient
include HTTParty
format :json
base_uri "http://reddit.com/r/"
def self.get_category(category, *opts)
opts.reverse_merge(limit: 25)
get("/#{category}.json", opts)
end
end
This way HTTParty handles JSON parsing for us and does not attempt to an convert an empty response. Its also much easier to test separately.
However you should still check if the response was successful before trying to use it:
#response = RedditClient.get_category(category)
if #response.success?
attrs = #response['data']['children'].map do |child|
{
category: category,
link: child['data']['url'],
title: child['data']['title']
}
end
Pic.create!(attrs)
else
# log it or raise some sort of error
end
Note that you where passing an array containing a single hash to .create. You can instead pass an array of hashes and it will insert the records in a single SQL insert statement.
When you get errors like this, you should always dump the actual response so you can inspect it. The fact you got a error for a nil with code doing stuff like ['data']['children'] means Id guess you got a JSON response, but one that is missing one of the first items (e.g. ['data'] returned nil).
Dont just assume every request is successful, many things can make a HTTP fail. Its possible that you get a valid JSON response back, just not the one you are expecting, for example an error message which would have told you the problem.
Also even with a 10 second delay, you may be hitting a rate limit (never tested Reddit personally), but read the rules
Many default User-Agents (like "Python/urllib" or "Java") are drastically limited to encourage unique and descriptive user-agent strings.
This kind of errors are most common in ruby or rails. Can be handled in multiple ways. As #Stefan suggested you can use any of the bellow.
Most simply like this
response = HTTParty.get('http://reddit.com/r/#{category}/.json?limit=25')
if response.success?
response_body = response.body
# continue
end
or
response = HTTParty.get('http://reddit.com/r/#{category}/.json?limit=25')
case response.code
when 200
puts "Good!"
# Continue your parsing
when 404
puts "NOT FOUND!"
when 500...600
puts "ERROR #{response.code}"
end
or
begin
HTTParty.get('http://reddit.com/r/#{category}/.json?limit=25')
rescue HTTParty::Error
# HTTParty errors like Not found
rescue StandardError
# StandardError like Timeout
else
# continue
end

Rails adds an extra 'command' object to my POST params

Rails 4.1 is adding a strange object to my POST parameters, which is a duplicate of the data I post.
As a very basic test, I post a simple {"msg"=>"hello word!"} from Angular:
$http.post('/commands/save.json', {msg:'hello word!'}).
Rails gets:
Started POST "/commands/save.json" for ::1 at 2015-01-08 10:15:55 -0800
ActiveRecord::SchemaMigration Load (0.3ms) SELECT `ngconf_schema_migrations`.* FROM `ngconf_schema_migrations`
Processing by CommandsController#save as JSON
Parameters: {"msg"=>"hello word!", "command"=>{"msg"=>"hello word!"}}
{
"msg" => "hello word!",
"controller" => "commands",
"action" => "save",
"format" => "json",
"command" => {
"msg" => "hello word!"
}
}
Commands Load (0.3ms) SELECT `ngconf_commands`.* FROM `ngconf_commands`
Completed 200 OK in 16ms (Views: 1.5ms | ActiveRecord: 12.8ms)
Basically I am trying to understand where does this come from and how to stop it. I do not remember Rails 4.0 doing this.
"command" => {
"msg" => "hello word!"
}
This is coming from ParamsWrapper. You can disable this by specifying wrap_parameters false in the controller. If you would like to disable it application wide, edit your config/initializers/wrap_parameters.rb and set the :format option to an empty array as per the comments. As an example
# Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: []
end

why I can not accept white spaces on field for save in ruby on rails?

I am trying to save a form with rails, its a simple one, and everytime I try to send a name with a space (like john smith) I dont actually get an error, it returns succcess, but does not save anything, when I try johnsmith then it works.
I checked on my model and I have this
validates :first_name, :allow_blank => true, :format => { :with => /\A[a-zA-Z]+\z/, :message => "Only letters allowed" }
validating only letters, but accepting spaces, still, when I try, no success.
At my controller I have something like this.
name = params[:name].to_s
and later
#user.atributes = { :weight => weight, :name => name ... and so on
at the end I only make a #user.save
Any idea how to avoid this problem? I do want to accept spaces on the names, but without getting into security problems.
Thanks
result of the post in my console
Started POST "/users/custom" for 192.168.1.21 at 2013-05-21 17:51:06 -0600
Processing by UsersController#custom as JS
Parameters: {"name"=>" new user", "lastname"=>" my last name", "mail"=>"newuser#gmail.com", "sex"=>"0" ... n so on}
User Load (0.1ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 6 LIMIT 1
(0.1ms) BEGIN
(0.3ms) UPDATE `users` SET `first_name` = ' new user', `ssn` = 0, `updated_at` = '2013-05-21 23:51:06' WHERE `users`.`id` = 6
(1.2ms) COMMIT
Rendered users/custom.html.erb within layouts/application (0.1ms)
Completed 200 OK in 16ms (Views: 11.0ms | ActiveRecord: 1.7ms)
Your regex is wrong. You're accepting only letters, whitespace is not a letter. Try something like this: \A[a-zA-Z,\s]+\z
BTW rubular is pretty cool tool, if you need to test your regexps.
http://rubular.com/
About the validation message not showing up:
If you're doing asynchronous request, you'll need to make your validation on the client side. There are some gems which can help you with this, e.g. client side validations gem.
Also, if you're using jQuery.ajax() you can use its callback to perform an action after the call (notify user of success or do whatever with DOM you want to):
$.ajax({
url: "http://some/url.com",
// rest of your ajax call
}).done(function (data) {
console.log("Your data:", data); // this will be run after the async. call
});
If you need to debug things like this try pry. Just add to your gemfile:
group :test, :development do
gem 'pry', '~> 0.9.12'
end
Run bundle install, restart server and then you can add:
binding.pry
wherever you want to stop code execution and inspect current state of your app enviroment in the console.
In your case it would be somewhere at the end of UsersController#custom method. You can then check in your terminal value of #user. Methods #user.valid? and #user.errors will tell you if your #user object is valid and show you an array with all validation errors associated with the object.

Problem with Rails 3 and AMF , rails3-amf, RocketAMF

im trying to get AMF to work with Rails3.
I have succesfully installed rails3-amf-0.1.0 gem and the RocketAMF-0.2.1 gem.
In my app there is a controller with the following code:
def getRandomCards
#incoming = params[0]
#cards = Cardvo.first
respond_with(#cards) do |format|
format.amf { render :amf => #cards.to_amf}
end
end
through a call from Actionscript i would like to return some data in amf format.
further more, as mentioned in the instructions for rails3-amf i did the following.
in my production.rb under config/environment i added the line
config.rails3amf.map_params :controller => 'CardvosController', :action => 'getRandomCards'
an my amf gateway got
config.rails3amf.gateway_path = "/gateway"
The problem is:
Any call from Actionscript / Flash raises the following
(taken from the log )
Started POST "/gateway" for 192.178.168.1 at Fri Nov 19 15:13:28 +0100 2010
Processing by CardvosController#getRandomCards as AMF
Parameters: {0=>100.0}
[1m[36mSQL (0.4ms)[0m [1mSHOW TABLES[0m
[1m[35mCardvo Load (0.2ms)[0m SELECT `cardvos`.* FROM `cardvos` LIMIT 1
Completed 200 OK in 13ms (Views: 0.9ms | ActiveRecord: 0.5ms)
NoMethodError (undefined method `constructed?' for #<RocketAMF::Envelope:0x39ba868>):
The Amf file is created but the method, which is in remoting.rb from RocketAMF could not be found.
I think the error is thrown at request_parser.rb from Rails3AMF asking for constructed?
# Wrap request and response
env['rack.input'].rewind
env['rails3amf.request'] = RocketAMF::Envelope.new.populate_from_stream(env['rack.input'].read)
env['rails3amf.response'] = RocketAMF::Envelope.new
# Pass up the chain to the request processor, or whatever is layered in between
result = #app.call(env)
# Calculate length and return response
if env['rails3amf.response'].constructed?
For me it seems it is looking at the wron class for the method.
Where
NoMethodError (undefined method `constructed?' for #RocketAMF::Envelope:0x39ba868):
the essential part is
RocketAMF::Envelope:0x39ba868
which should be
RocketAMF:ANOTHER_CLASS:Envelope:0x39ba868
Am i right and where the heck is the error ?
Any help would be appreciated!
chris

Error during failsafe response: Ruby on Rails 3

I have a form_tag that works fine using html, but when I use ajax with the remote => true I am getting this error:-
My terminal log shows:-
Started GET "/" for 127.0.0.1 at 2010-11-01 01:19:49 +0000
Processing by HomepagesController#index as HTML
Homepage Load (0.6ms) SELECT "homepages".* FROM "homepages"
Rendered homepages/index.html.erb within layouts/application (23.0ms)
Completed 200 OK in 40ms (Views: 27.3ms | ActiveRecord: 0.6ms)
Error during failsafe response: incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string)
* then a load of cleaner.rb stuff
then:-
Started GET "/homepages?utf8=%E2%9C%93&search=hom" for 127.0.0.1 at 2010-11-01 01:19:56 +0000
Processing by HomepagesController#index as JS
Parameters: {"utf8"=>"✓", "search"=>"hom"}
Homepage Load (0.5ms) SELECT "homepages".* FROM "homepages" WHERE (section LIKE '%hom%')
Rendered homepages/index.js.erb (2.9ms)
Completed in 19ms
In my index.js.erb I have:-
$("testsearch").update("<%= escape_javascript(render(#homepages))%>");
and in my Controller I have:-
def index
#homepages = Homepage.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #homepages }
format.js { render :layout => false }
end
in my view I have:-
which prints #homepages using a table using <% #homepages.each do |homepage| %> which is not being updated.
Anyone have any ideas as to why I get this error.
I have cracked it by going onto an IRC chat room (irc.freenode.net RubyonRails) and a ProjectZen (human being somewhere out there in the ether) helped me to get it working.
Apparently what was happening was that I was following Ryan Bates who does many extremely good Railcast videos, but he builds on previous Railcast. Therefore in his 205 Railscast, which deals with Ajax calls, he did not mention that you must have:-
format.js in the action in the controller.
His xxxx.searchxxxxx needs to be created in the controller or model.
And that when I did :-
<%= render(#homepages)%> <!-- (in his case <%= render(#products)%>) -->
The render was looking for a partial called "_homepage" (not "homepages") (I did not even have a partial therefore I got the UTF8 to ASCII error).
And then in "_homepage" I would add my code to render the results.
What I have now done in my index.html.erb is to put <%= render(#homepages)%>, in the (div id = testsearch) in place of the code I use to render #homepages and then place that code in a partial "_homepage". Now I can use "_homepage" for the html and the Ajax call.
At the moment I have a slight problem in that it is rendering all the data in the"#homepages" as many times as the number of records. At the moment I do not know why, but at least the Ajax call is working.

Resources