Passing params Hash in methods in rails - ruby-on-rails

I have the following code in the controller
def show
client = GameAccounts::GameAccountsClient.new
..
json = client.get_accounts( ..)
..
end
I have the following code in GameAccountsClient
def get_accounts(..)
response = query_account(CGI.escape(params[:name])
JSON.parse(response.body)
end
I have the above code and i am not sure how to pass params[:name] while calling the get_accounts method in the controller. Can anyone help me out with passing the hash's in methods in rails ? .Thank you

If i understand it correctly, you just need to pass the params[:name] to your model method.
def show
client = GameAccounts::GameAccountsClient.new
json = client.get_accounts(params[:name])
end
def get_accounts(name)
response = query_account(CGI.escape(name)
JSON.parse(response.body)
end

Related

Params is nil on entry into controller method

Rails 5.2
In my inventories_controller.rb, I have the following:
before_action :fetch_product, only: [:show]
def show
........
end
def fetch_product
if params.has_key?(:sku)
#product = Product.get_product(params)
end
end
This works fine, when I do: http://0.0.0.0:3000/sku/12345678
I am trying to implement search functionality, so I modified nventories_controller.rb as follows:
def fetch_product
if params.has_key?(:search) && !params[:search].blank?
product = Product.find_by_sku(params[:search])
if !product
params = params.except[:search]
redirect_to product_show_path, alert: 'Product was not found'
end
params = params.merge!(:sku, product.sku)
end
if params.has_key?(:sku)
#product = Product.get_product(params)
end
end
When I do: http://0.0.0.0:3000/sku/12345678
I get an instant error message:
undefined method `has_key?' for nil:NilClass
Using my debugger, I find that on entry into the fetch_product method, params is nil
Any idea what's going on?
params = params.merge!(:sku, product.sku) modifies the hash in place and returns nil, don't do that assignment, just call params.merge! (if you still want to do the assignment, remove the "!").
Personally, I wouldn't modify the params hash unless it's really really needed, I would use another variable.

How to refactor ruby rest-client get method

I'm using Rubys rest-client gem to make a call to Google API and want to shorten the url part.
Current code:
class GoogleTimezoneGetter
def initialize(lat:, lon:)
#lat = lat
#lon = lon
#time_stamp = Time.new.to_i
end
def response
response = RestClient.get "https://maps.googleapis.com/maps/api/timezone/json?location=#{#lat},#{#lon}&timestamp=#{#time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}"
JSON.parse(response)
end
def time_zone
response["timeZoneId"]
end
end
I would like to be able to do something like:
def response
response = RestClient.get (uri, params)
JSON.parse(response)
end
But I'm struggling to find out how to do so.
To make the class a bit tidier, I'd like to break the url down into 'uri' and 'params'. I think the rest-client gem allows you to do this but I can't find specific examples.
I want to put the
{#lat},#{#lon}&timestamp=#{#time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}"
in to a 'params' method and pass that to the RestClient.get method.
Have you check the rest-client gem readme?
They did give a specific example on this (below example quoted from the readme)
RestClient.get 'http://example.com/resource', {params: {id: 50, 'foo' => 'bar'}}
In your case, it should be something like this
def url
"https://maps.googleapis.com/maps/api/timezone/json"
end
def params
{
locations: "#{#lat},#{#lon}",
timestamp: #time_stamp,
key: GOOGLE_TIME_ZONE_KEY
}
end
def response
response = RestClient.get(url, params: params)
JSON.parse(response)
end
rest-client already accepts a hash for params. If you prefer a bunch of little methods on your class, you can divide out each step to a method and keep everything readable.
class GoogleTimezoneGetter
def initialize(lat:, lon:)
#lat = lat
#lon = lon
#time_stamp = Time.new.to_i
end
def response
response = RestClient.get gtz_url, params: { gtz_params }
JSON.parse(response)
end
def time_zone
response["timeZoneId"]
end
def gtz_url
"https://maps.googleapis.com/maps/api/timezone/json"
end
def gtz_params
return {location: "#{#lat},#{#lon}", timestamp: #time_stamp, key: GOOGLE_TIME_ZONE_KEY }
end
end

Update API throwing Parameter missing error in Rails 4

I am trying to learn and write an update API and to start small I am passing a single params in the API and and try to get the response.
the controller :
module Api
module V1
class OrderApiController < ApiController
def order_update
response = Hash.new
result = Hash.new
#order = Order.find(params[:id])
if #order.update_attributes(order_params)
result['order_id'] = order.id
response['result'] = result
response.merge! ApiStatusList::OK
else
response.merge! ApiStatusList::INVALID_REQUEST
end
render :json => response
end
private
def order_params
params.require(:order).permit( :id)
end
end
end
end
the api route in routes.rb is:
match 'mobile/order_update' =>'order_api#order_update'
The url link what I give is
http://localhost:3000/api/v1/mobile/order_update?key=docket&id=1
However this throws the following error
ActionController::ParameterMissing at /api/v1/mobile/order_update
param is missing or the value is empty: order
I dont know what am I doing wrong. I am new to Rails as well as API generation. Please help
This is caused by the order_params method, in which you're requiring order(expecting order to be a nested hash), whereas, you're not nesting it.
An approach you could take is to visit:
http://localhost:3000/api/v1/mobile/order_update?key=docket&order[id]=1
Also, I see you're setting #order instance variable, but in your control block(if #order.update_attributes), you're using a local variable which would give you another error.
I'd recommend you go through the Hartl Tutorial as there are a lot of things you'd be able to learn from there
UPDATE
Based on the new error mentioned in the comment, I think you should rather be visiting:
http://localhost:3000/api/v1/mobile/order_update?order[key]=docket&id=1
This is assuming your orders table has a column key based on the params being set
Also, change your order_params to:
private
def order_params
params.require(:order).permit( :key) #since you cannot update a primary key, but I guess you want to update the key column
end
The solution I used is as follows
In my order_api_controller.rb , I have Changed
def order_update
response = Hash.new
result = Hash.new
#order = Order.find(params[:id])
if #order.update_attributes(order_params)
result['order_id'] = order.id
response['result'] = result
response.merge! ApiStatusList::OK
else
response.merge! ApiStatusList::INVALID_REQUEST
end
render :json => response
end
and edited it to this
def order_update
response = Hash.new
result = Hash.new
debugger
#order = Order.find(params[:order][:id]) # passed the order symbol into params
if #order.update_attributes(order_params)
result['order_id'] = #order.id # Modified local variable to instance variable as per oreoluwa's suggestion
response['result'] = result
response.merge! ApiStatusList::OK
else
response.merge! ApiStatusList::INVALID_REQUEST
end
render :json => response
end
And used the url as Follows
http://localhost:3000/api/v1/mobile/order_update?key=docket&order[id]=1
This seems to do the trick

Ruby on Rails 4. Can i pass objects through flash scope

I have a controller and need to pass objects which validation fail to another controller action to process them and show to user:
class PersonController
def save_persons
invalid_persons = ... #array of Person.new objects
flash[:invalid_persons] = invalid_persons
redirect_to action: :fix_errors
end
def fix_errors
invalid_persons = flash[:invalid_persons]
invalid_persons.each do |invalid_person|
puts invalid_person.errors #here i get exception!
end
end
end
When i try to puts invalid_person.errors i get error: undefined method errors for #Hash:0x007fd594e79098>. It seems that rails transform my objects array to some hash
Can you suggest me, what is the right way to pass some object through flash?

Catching UTM Params in Rails

I am trying to catch the UTM Params in the URL to add Source, Campaign etc to a User Account.
Sadly, I can't seem to figure out how to catch those params. As of know I following the Blog Article http://www.matthuggins.com/articles/tracking-new-user-registrations-by-source-search-terms
So, in my Application Controller I have following:
ApplicationController.class_eval do
before_filter :capture_referrer
protected
def capture_referrer
session[:referrer] = request.env['HTTP_REFERER'] if !session[:referrer]
end
end
In the create Action in the user controller
#user.referrer = session[:referrer]
and in the USer Model itself:
def set_traffic_source
if self.referrer
url = URI.parse(self.referrer)
self.source ||= uri.host.downcase.gsub(/^www\./, '')
self.traffic_keywords ||= search_termins(uri)
end
end
This all works fine, for catching the referer - But I actualy want to read out the UTMs passed into by the URI. How would I go about this?
Use params to access them:
params[:utm_source]
params[:utm_campaign]
params[:utm_medium]

Resources