Reputation: 21
I have the following url /purchases/3/payments/new
, which I get in the purchases controller by
link_to 'pay', purchase_path(purchase)+new_payment_path
Now in the payments controller I would need to have the purchase object, or its id at least from where it was invoked. I tried using a param, but is there any other way ? Thanks
Upvotes: 1
Views: 264
Reputation: 76784
Routes
I immediately highlighted this as a problem:
purchase_path(purchase)+new_payment_path
This is really bad (configuration over convention) - you'll be much better using the actual path helper to load the resource you need (keeps it DRY & conventional)
--
Nested
As mentioned by Jon M
, your solution will come from the use of nested resources
:
#config/routes.rb
resources :purchases do
resources :payments # -> domain.com/purchases/:purchase_id/payments/new
end
This will allow you to use the route path as described by Jon
.
--
Controller
in the payments controller I would need to have the purchase object, or its id
By using nested resources, as described above, the route will hit your payments
controller and have the following param
available:
params[:purchase_id]
Note the naming of the param (only the nested
resource is identified with params[:id]
), as demonstrated in the docs: /magazines/:magazine_id/ads/:id
I would recommend using the following code in your controller:
#app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
def new
@purchase = Purchase.find params[:purchase_id]
end
end
Upvotes: 0
Reputation: 3548
Using params makes sense.
You should be able to get the purchase ID like this in the payments controller:
params[:purchase_id]
However, need to setup your routes in a specific way to do this:
resources :purchases do
resources :payments
end
Then you can create the link in the view like this:
link_to 'pay', new_purchase_payment_path(purchase)
Have a look at these docs too: http://guides.rubyonrails.org/routing.html#nested-resources
Upvotes: 2