Asking Models For Their URL
April 27th, 2007
In my Rails projects, I sometimes have trouble remembering all my complex routes. Not only that, it’s a bummer to have to type out that long line every time I need to generate a URL.
So instead, I let the models tell me their URLs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Article < ActiveRecord::Base belongs_to :category include ActionController::UrlWriter default_url_options[:host] = "www.example.com" def url category_article_url(self.category, self) end def path category_article_path(self.category, self) end end |
Now I can say @article.url
, which will generate
http://www.example.com/categories/123/articles/456-my-article
or @article.path
, which will give me just the path:
/categories/123/articles/456-my-article
April 28th, 2007 at 06:58 PM
With no other modifications? Which version of Rails? I’m running on Edge and I get method_missing if I try to call the routes from within the model.
April 28th, 2007 at 10:33 PM
Hi Tim,
Good catch. You do have to “include ActionController::UrlWriter” in order for this to work.
Sorry I forgot to include that! I’ve updated the code example as well.
April 28th, 2007 at 10:35 PM
You might also have to set default_url_options[:host] for this to work.
April 30th, 2007 at 07:59 AM
Won’t this lead to MVC complications in the future?
April 30th, 2007 at 08:11 AM
Possibly, but on the other hand if you change your routes you only have to update your urls once, instead of throughout your application. In my opinion this doesn’t violate the MVC model because you’re attaching a behavior to an object. Essentially you’re asking an object “tell me your URL”.
May 3rd, 2007 at 02:02 PM
Interesting tip, though I have to wonder the same think as bryanl – is this overlapping the controller and the model? Traditionally, the controller can work with the model, but the model shouldn’t know anything about the controller. Perhaps a helper would be better and not pollute the model with controller concepts? You’ll still remain DRY and the MVC architectural pattern will remain complication-free?