Multiple, custom URLs for Rails 3 resources without ID
In my app I've got various resources that I want to access via multiple URLs. For example, an invoice can be accessed via:
/invoices/:id
By the issuer of the invoice, and also via:
/pay/:payment开发者_如何学JAVA_key
By the payer.
The latter URL does not require authentication (hence the secrefied payment_key).
The issue is how to get automatic URL helper methods for the custom URL. Usually you could use to_param
to customize the resource URL (as described here), but that's not adequate in this case because I still want to retain the default resource URL.
If I create the helper methods by declaring a named route:
/pay/:payment_key, :as => :invoice_payment
Then I would expect invoice_payment_url(invoice)
to include invoice.payment_key
but it doesn't. Rails uses the invoice ID instead (similar to the behaviour reported here)
This seems like it's broken.
So I've been defining the url helpers for this resource manually.
def invoice_payment_path (invoice)
url_for :controller => "invoices",
:only_path => true,
:action => "pay",
:payment_key => invoice.payment_key
end
def invoice_payment_url (invoice)
url_for :controller => "invoices",
:only_path => false,
:action => "pay",
:payment_key => invoice.payment_key
end
Wondering if there is a DRYer way to do this?
RESTful is about resources. So are you sure the "payment" and "invoice" resources the same thing in your system? To me, it is more like a system design issue than a routing issue.
Another thought is using nested resources. You can view either "/payments/:id/invoices" or "/invoices/:id/payments", both make sense to me.
Yan
精彩评论