Asking Models for their URL
May 22nd, 2007
[UPDATE] This article accidentally got deleted, along with all the comments. Shame on my trigger-happy mouse finger, which clicked “OK” without reading the contents of the delete confirmation. So, thanks to Jeff Whitmire who found the text of the article in his RSS feed. Sorry to those who commented – there were some good thoughtful ones.
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
1 Response to “Asking Models for their URL”
Sorry, comments are closed for this article.
June 1st, 2007 at 03:54 AM
Have you checked out SimplyPresentable? This does the same kind of thing:
<%= link_to ‘Show Foo’, present(@foo).url %>
Saves having to fill your models with view/controller code