4

I have two models, say User and Group

I know I can access the show action to each object with the different solutions:

# PATH
link_to user.name, user_path(user)
link_to group.name, group_path(group)

# URL
link_to user.name, user_url(user)
link_to group.name, group_url(group)

But Rails' magic occurs when

# PATH
link_to user.name, user_path(user)
link_to group.name, group_path(group)
# is equivalent to
# PATH
link_to user.name, user
link_to group.name, group

Is there a way I can interpolate to get the url?

I could write something like this:

link_to user.name, send("#{user.class.name.downcase}_url", user)

But is there a cleaner way?

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206
  • 1
    Can you give clarification about why you need to use the URL rather than the path? One possible approach is to use something like what inherited_resources does. It creates resource_path and resource_url helpers that return the path/url for the appropriate object given the context. – Coenwulf Feb 07 '14 at 16:56
  • I need resource_url helper because it will be sent in an email. – Augustin Riedinger Feb 07 '14 at 18:03

2 Answers2

6

url_for calls polymorphic_path() with the object you pass when you pass in an ActiveRecord (as well as some other cases). you can use polymorphic_url instead to get what you want.

link_to object.name, polymorphic_url(object)
Coenwulf
  • 1,937
  • 2
  • 15
  • 23
1

Unfortunately there's no way to tell link_to to use the url when you pass only the model in. You'll have to stick to user_url.

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55