views:

101

answers:

2

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?

+1  A: 

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.

Michael Gattuso
I think it actually calls #to_param on your object. That's what you can over-ride if you want the URL to feature an seo-friendly-url for example - or anything that isn't the record's id.
NeilS
+3  A: 

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.

ScottD
Just to clarify, I believe it does `@workshop.class.to_s.underscore` in case there are multiple words in the class name. For instance: UserRole.class.to_s.underscore = 'user_role'. Add on a `.pluralize` and you're good to go!
Topher Fangio