0

I need to call method for each user(admin part), which has email parameter. It is a function for paying in PayPal, but I can't use redirection in instances.

Code from my view payments.erb:

 % @users.each do |user| %>
<li>
  <%= user.email %>
  <%= link_to "Pay", user.pay(user.email) %>
</li>

Code of pay method

def pay email
//making post request to PayPal
//res = clnt.post(uri, data, header)
//if res.status ==200
//redirect_to PayPal
//else redirect_to :back
end

How I can pass parameters or how can I reorganize this all ? Do I need to create an action in pages controller, or can I use some after_call_pay function ?

2 Answers 2

1

It isn't the controllers job to respond to instance methods. It's the controllers job to respond to requests.

So you want to be able to link_to an action that responds to mydomain.com/users/1/pay or something like that.

In routes

resources :users do
  member do
    post 'pay'
  end
end

then in your controller

def pay
  @user = User.find(params[:id])
  #route user to paypal or somewhere else based on some condition
end

And finally in the view

<%= link_to "Pay", pay_user_path(user) %>
Sign up to request clarification or add additional context in comments.

2 Comments

DVG, not user should call this function, but admin, which will be paying TO users.. I can't use params[:id]. What you can suggest then ?
I believe you would want to put it on the users controller, because that is the resource you are doing an operation on, albeit the admin is initiating it and presumably you will have some kind of authentication/authorization around this action to prevent non-admins from initiating it.
1

I think you should be handling this in a form rather than a link.

If payment is a method associated with a user object then you would want to do something like this:

View -

<%= form_for @user, :url => { :action => "make_payment" } do |f| %>
    #any form fields associated with making the payment (ie credit card number)
    <%= f.submit %>
<% end %>

This would route the form to the Users_controller and to an action named "make_payment". Make sure to provide a route to this action in your config/routes file as this will not be reachable if you are using the standard resourceful routing.

Controller -

def make_payment
   @user = User.find(params[:id])
   user.submit_payment(params[:credit_card_num])
   redirect_to @user
end

That should accomplish what you are looking to do. Check here for some more explanation on the rails form helpers http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.