How to use link_to object in Rails
So you want to dry up your use of link_to a tiny bit?
In a lot of Rails code you see stuff like link_to user.name, user a ton of times in one application.
Some people go ahead and define a link_to_user(user) helper method. While this is sometimes necessary, in a lot of cases it is not.
Instead, to dry this up, you can simply define to_s for the class of object that you’re linking to, and then just use link_to user, user or whatever object you’re dealing with.
Like this:
This works because link to is calling to_s on the second argument. As far as I can tell, “#{xyz}” calls to_s on whatever xyz evaluates to (that’s why puts “#{nil}” doesn’t give an error)).
It would be nice to see something like url ||= url_for(args.first) in link_to, but this might cause trouble elsewhere. However it would let you just do link_to user, which would be sexy.
Also note that link_to is using url_for(options). This means that you don’t need to do link_to user.name, user_path(user).


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago