If you call url_for
on a model object:
<%= url_for(@workshop) %>
The docs for url_for
say it calls @workshop.to_s
which results in:
/workshops/5
But if I just call to_s on the model, I don't get the route
- how does url_for do this?
If you call url_for
on a model object:
<%= url_for(@workshop) %>
The docs for url_for
say it calls @workshop.to_s
which results in:
/workshops/5
But if I just call to_s on the model, I don't get the route
- how does url_for do this?
I don't know enough of ruby or rails to question the documentation but what is really happening is that it is calling @workshop.id.to_s
to get the 5 (the id being the primary key in the database). To call straight Workshop.to_s will get you the memory reference of the object.
Inside ActionController it is calling a method called polymorphic_url. Basically it inspects the type of Object that @workshop is and uses that plus its ID to construct the route. So if @workshop.class = Workshop, rails can do a to_s.downcase on that and then start building the route based on the other url_for options and the action. The code is in the module PolymorphicRoutes in the rails source.