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

6 Responses to “Asking Models For Their URL”

  1. Tim Connor Says:

    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.

  2. Ryan Heneise Says:

    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.

  3. Ryan Heneise Says:

    You might also have to set default_url_options[:host] for this to work.

  4. bryanl Says:

    Won’t this lead to MVC complications in the future?

  5. Ryan Heneise Says:

    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”.

  6. James Higginbotham Says:

    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?

Leave a Reply