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 ?

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
lol
  • 1
  • 1

2 Answers2

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) %>
DVG
  • 17,392
  • 7
  • 61
  • 88
  • 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 ? – lol Jul 20 '12 at 06:22
  • 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. – DVG Jul 20 '12 at 13:35
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

louism2
  • 350
  • 4
  • 18