Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Pretty URLs for Rails 3.x and Rails 2.x without the need for any external plugin, but with a little hack, unfortunately.</p> <p>routes.rb</p> <pre><code>map.resources :posts, :except =&gt; [:show] map.post '/:year/:month/:slug', :controller =&gt; :posts, :action =&gt; :show, :year =&gt; /\d{4}/, :month =&gt; /\d{2}/, :slug =&gt; /[a-z0-9\-]+/ </code></pre> <p>application_controller.rb</p> <pre><code>def default_url_options(options = {}) # resource hack so that url_for(@post) works like it should if options[:controller] == 'posts' &amp;&amp; options[:action] == 'show' options[:year] = @post.year options[:month] = @post.month end options end </code></pre> <p>post.rb</p> <pre><code>def to_param # optional slug end def year published_on.year end def month published_on.strftime('%m') end </code></pre> <p>view</p> <pre><code>&lt;%= link_to 'post', @post %&gt; </code></pre> <p>Note, for Rails 3.x you might want to use this route definition:</p> <pre><code>resources :posts match '/:year/:month/:slug', :to =&gt; "posts#show", :as =&gt; :post, :year =&gt; /\d{4}/, :month =&gt; /\d{2}/, :slug =&gt; /[a-z0-9\-]+/ </code></pre> <p>Is there any badge for answering your own question? ;)</p> <p>Btw: the <a href="http://github.com/rails/rails/blob/master/actionpack/test/dispatch/routing_test.rb" rel="nofollow noreferrer">routing_test</a> file is a good place to see what you can do with Rails routing.</p> <p><strong>Update:</strong> Using <code>default_url_options</code> is a <strong>dead end</strong>. The posted solution works only when there is <code>@post</code> variable defined in the controller. If there is, for example, <code>@posts</code> variable with Array of posts, we are out of luck (becase <code>default_url_options</code> doesn't have access to view variables, like <code>p</code> in <code>@posts.each do |p|</code>.</p> <p>So this is still an open problem. Somebody help?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload