noli
noli

Reputation: 15996

How can I generate this custom URL more succinctly in Rails?

get '/:user_id/wants/:id' => 'wanted_items#public_view', :as => 'public_wanted_item'

public_wanted_item GET    /:user_id/wants/:id(.:format) {:controller=>"wanted_items", :action=>"public_view"}

/username/wants/itemname

The problem is that in order to generate this in my views, I have to user a pretty verbose construct, where I specify :user_id and :id explicitly:

ruby-1.9.2-p0 :012 > app.public_wanted_item_path(:user_id => item.user, :id => item)

Is there any way I can make this call more concise, as I will be using it a lot in my application?

Thanks


Edit: I found a solution that works.. Pasted below

It seems to work just as well if I use the following construct, which was what I was hoping for.. .. though I'm not sure exactly why it works..

ruby-1.9.2-p0 :002 > app.public_wanted_item_path item.user, item

Because the next one doesn't work, but throws an error:

ruby-1.9.2-p0 :004 > app.public_wanted_item_path([item.user, item])

Upvotes: 0

Views: 62

Answers (2)

mu is too short
mu is too short

Reputation: 434665

This sounds like a job for an application helper. You could add something like:

def item_path_for(item)
    app.public_wanted_item_path(:user_id => item.user, :id => item)
end

to your app/helpers/application_helper.rb and then you could use

<%= item_path_for(pancakes) %>

in your views (or the HAML equivalent) or

include ApplicationHelper
#...
path = item_path_for(pancakes)

elsewhere in your code.

Upvotes: 4

fl00r
fl00r

Reputation: 83680

app.public_wanted_item_path(:user_id => item.user.id, :id => item.id)

Upvotes: 0

Related Questions