简体   繁体   中英

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

  • I've set up the following route in Rails 3

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

  • Which gives the following in Rake Routes:
public_wanted_item GET    /:user_id/wants/:id(.:format) {:controller=>"wanted_items", :action=>"public_view"}
  • And it produces the following URL, which is exactly what I want:

/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])

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM