I basically want to use link_to to link to the index method of a controller. I tried:
<%= link_to 'Recipes', Recipe %>
but that outputs:
<a href="/recipes/Recipe">Recipes</a>
Which is clearly not right, if it left off that last bit it would do exactly what I want it to. I thought that with RESTful stuff I somehow would start to leave out the action or something like that. What am I misunderstanding?
-
With the restful routes, the majority of the time you're expected to call a helper method to generate the route.
eg:
link_to 'Recipes', recipes_path
There is an optimization where you can just pass in a recipe object, and it will call the helper method for you behind the scenes: eg:
link_to 'Recipe X', @recipe
is the same as
link_to 'Recipe X', recipe_path(@recipe)
However, it's just a special case.
What you are doing is passing The recipe class itself, not a valid recipe object. As rails doesn't know to handle this, as a fallback it just calls
.to_s
on whatever you've given it, and then gives that torecipe_path
, which is why you see the strange URL.Tip: Use the
_path
helper methods rather than the_url
methods._url
gives you a full URL such ashttp://stackoverflow.com/recipes/5
whereas_path
just gives you/recipes/5
.
The problem with the full URL is that a lot of the time in production your rails app is running as a mongrel sitting behind a load balancer, so it thinks it's host name is actually1.2.3.4
(or whatever the internal LAN IP is) rather than the real URL, and so will serve broken links.Ben Scofield : Your first example should use recipes_path - you want the index action.Frew : Excellent! Thanks!From Orion Edwards
0 comments:
Post a Comment