Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails link_to object interpolation with url instead of path

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?

like image 811
Augustin Riedinger Avatar asked Mar 21 '23 15:03

Augustin Riedinger


1 Answers

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)
like image 100
Coenwulf Avatar answered Mar 23 '23 11:03

Coenwulf