views:

32

answers:

2

I need to generate links in my views using the url helpers such as user_path(@user), the catch is, in some cases I don't know what model I am creating this link for i.e. whether it is a user or a store or someting else

I would like to be able to determine this on the fly and call the appropriate view helper, currently I am doing the following, but I am wondering if there is a drier way of doing it.

if object.class == "Store"
   store_path(object)
elsif object.class == "User"
   user_path(object)
...etc
+1  A: 

url_for(object) does what you need:

If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter, you‘ll trigger the named route for that record. The lookup will happen on the name of the class. So passing a Workshop object will attempt to use the workshop_path route.

If you are using link_to, then you can just pass the object as the URL:

<%= link_to 'Title', object %>
Phil Ross
This is what rails does internally, form_for and link_to among others just wraps url_for. You can choose whether you want a full URL or just the path with the :only_path option.
elektronaut
Thanks this works just perfect!
badnaam
A: 

Sure, use send to dynamically choose the method name

send("#{object.class.name.downcase}_path", object)
Larry K
This works too!
badnaam