How to call controller method from view RAILS 4.0 - ruby-on-rails

I think I stated the title of this question right, but this is the issue:
I have the following in my SurveysController-
def pull_responses
call= "/api/v2/surveys/"
auth = {:username => "test", :password => "password"}
url = HTTParty.get("https://fluidsurveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = JSON.parse(url.body)
survey_ids = response["surveys"].map { |s| s["id"] }
survey_ids.each do |x|
call= "/api/v2/surveys/#{x}/responses/?_completed=1"
auth = {:username => "test", :password => "password"}
url = HTTParty.get("https://Fluidsurveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = JSON.parse(url.body)
response_count = response["count"]
Survey.create(y: response_count)
end
end
helper_method :pull_responses
All I am trying to do is put the variable response_count in my Surveys view. I may not need Survey.create(y: response_count), but that was a peice of one of my attempts to get this to work. Essentially, I just want to write this in a view:
puts response_count
What is the proper way to put that response into a view?

You need to assign the value to an instance variable (by adding # before the name) so that it will persist to the view:
#response_count = response["count"]
then in the view you can print it like so:
<%= #response_count %>

Related

Change params inside controller rails

How can I change params inside controller?
When I click the accept it will pass the status is approved but if diff <= 0 change status to rejected
View
<%= link_to 'Accept', friend_path(s, :request => {:status => 'Accepted'}), method: :put %>
into this
if diff <= 0
req_params[:status] = "Rejected"
#request.update(req_params)
end
end
private
def req_params
params.require(:request).permit(:status)
end
end
To modify your status param, you need to do the following:
params[:request][:status] = 'Rejected'
or
req_params[:request][:status] = 'Rejected'
Because your request take params like this:
Parameters => { some_param => 'Something', required => { permited1 => 'bla',
permited2 => 'bla2',
... } }
I hope that helps you

How to access the token created by iOS Stripe?

i successfully got generating tokens working on the ios side, and i have a heroku rails app set up. How do i retrieve this token on the server side?
getting the error `Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method []' for nil:NilClass):
app/controllers/login_controller.rb:11:in 'log_in'
here is my controller code:
class LoginController < ApplicationController
def index
end
def log_in
puts params
headers = {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY"}
query = {:username => params[:user][:username],
:password => params[:user][:password]}
#response = HTTParty.get('https://api.parse.com/1/login',
:query => query,
:headers => headers)
session[:session_token] = #response["sessionToken"]
session[:object_id] = #response["objectId"]
#object_id = session[:object_id]
#test = HTTParty.get("https://api.parse.com/1/classes/_User/#{#object_id}",
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" =>"APIKEY"} )
session[:stripe_acct_id] = #test["uid"]
end
def logout
logout = HTTParty.post('https://api.parse.com/1/logout',
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token]})
reset_session
redirect_to :controller => "login"
end
def deauthorize
#object_id = session[:object_id]
HTTParty.post("https://connect.stripe.com/oauth/deauthorize",
:basic_auth => { :username => ENV['STRIPE_SECRET'] },
:query => { client_id: ENV['STRIPE_CONNECT_CLIENT_ID'],
stripe_user_id: session[:stripe_acct_id]})
end
end
In your controller add:
protect_from_forgery: :null, only: :log_in
For your error, it's because you don't send user object in your post request.

undefined method `values_at' for nil:NilClass when I use WashOut gem

I am new to WSDL.
Code (I have added in the view directly - for test): (Page: http://localhost:3000/ccapis )
require 'savon'
client = Savon::Client.new(wsdl: "http://localhost:3000/ccapis/wsdl")
result = client.call(:fetch_prizes, message: { :gl_id => "123456789" })
result.to_hash
And in the controller:
soap_action "fetch_prizes",
:args => { :gl_id => :string },
:return => [:array]
def fetch_prizes
glnumber = params[:gl_id ]
prize = Prize.where(:gl_id => glnumber)
prize_to_show = []
a_hash = {}
prize.each do |p|
a_hash = { :prize => p.prize.to_s, :score => p.score.to_s, :date => p.round_date.to_s }
prize_to_show.push a_hash
a_hash = nil
end
render :soap => prize_to_show
end
When I try and run this in the Console all are good and I can see the result.to_hash but when I go to http://0.0.0.0:3000/ccapis I get the error that I mentioned above.
Explanation of what I am trying to achieve:
I need to supply a WSDL for a client which fetches all the prizes based on a score.
If My approach is wrong please direct me to a document so I can have a read and get a better understanding. Thanks again.

Constantly get Authentication+failed.+API+credentials+are+incorrect

I'm trying to create simple PayPal Pay API operation, when I run this code from console it gave me response, that payment is created.
Now, when I'm tring to run it from my controller it gives me
Authentication+failed.+API+credentials+are+incorrect.
Here is my controller :
def pay
require 'httpclient'
require 'xmlsimple'
clnt = HTTPClient.new
credentials = {
'USER' => 'payer_1342623102_biz_api1.gmail.com',
'PWD' => '1342623141',
'SIGNATURE' => 'Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL '
}
header = {"X-PAYPAL-SECURITY-USERID" => "payer_1342623102_biz_api1.gmail.com",
"X-PAYPAL-SECURITY-PASSWORD" => "1342623141",
"X-PAYPAL-SECURITY-SIGNATURE" => "Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL ",
"X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "XML",
"X-PAYPAL-APPLICATION-ID" => "APP-80W284485P519543T"
}
data = {"actionType" => "PAY",
"receiverList.receiver(0).email"=> "denmed_1342605975_biz#gmail.com",
"receiverList.receiver(0).amount" => "10",
"currencyCode" => "USD",
"cancelUrl" => "http://127.0.0.1:3000",
"returnUrl" => "http://127.0.0.1:3000",
"requestEnvelope.errorLanguage" => "en_US"}
uri = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"
res = clnt.post(uri, data, header)
#xml = XmlSimple.xml_in(res.content)
payKey = #xml["payKey"].to_s()
payKey = payKey.tr("[]", "")
payKey = payKey[1..20]
redirect_to "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay?cmd=_ap-payment&paykey=#{payKey}"
end
Is everything ok ? Can anyone suggest reason my request fails ?
One good man found my error. I redirect user to the wrong url.
This line:
redirect_to "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay?cmd=_ap-payment&paykey=#{payKey}"
Should be:
redirect_to "https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=#{paykey}"
I got the same error: I realized I forgot to include
sandbox_email_address: xxx#example.com
in my yml file

How to use Rhodes without Rhosync or RhoConnect?

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.

Resources