Note that there are some explanatory texts on larger screens.

plurals
  1. POPretty (dated) RESTful URLs in Rails
    text
    copied!<p>I'd like my website to have URLs looking like this:</p> <pre><code>example.com/2010/02/my-first-post </code></pre> <p>I have my <code>Post</code> model with <code>slug</code> field ('my-first-post') and <code>published_on</code> field (from which we will deduct the year and month parts in the url).</p> <p>I want my <code>Post</code> model to be RESTful, so things like <code>url_for(@post)</code> work like they should, ie: it should generate the aforementioned url.</p> <p>Is there a way to do this? I know you need to override <code>to_param</code> and have <code>map.resources :posts</code> with <code>:requirements</code> option set, but I cannot get it all to work.</p> <hr> <p>I have it almost done, I'm 90% there. Using <a href="http://github.com/stengland/resource-hacks-plugin" rel="noreferrer">resource_hacks plugin</a> I can achieve this:</p> <pre><code>map.resources :posts, :member_path =&gt; '/:year/:month/:slug', :member_path_requirements =&gt; {:year =&gt; /[\d]{4}/, :month =&gt; /[\d]{2}/, :slug =&gt; /[a-z0-9\-]+/} rake routes (...) post GET /:year/:month/:slug(.:format) {:controller=&gt;"posts", :action=&gt;"show"} </code></pre> <p>and in the view:</p> <pre><code>&lt;%= link_to 'post', post_path(:slug =&gt; @post.slug, :year =&gt; '2010', :month =&gt; '02') %&gt; </code></pre> <p>generates proper <code>example.com/2010/02/my-first-post</code> link.</p> <p>I would like this to work too:</p> <pre><code>&lt;%= link_to 'post', post_path(@post) %&gt; </code></pre> <p>But it needs overriding the <code>to_param</code> method in the model. Should be fairly easy, except for the fact, that <code>to_param</code> must return <code>String</code>, not <code>Hash</code> as I'd like it.</p> <pre><code>class Post &lt; ActiveRecord::Base def to_param {:slug =&gt; 'my-first-post', :year =&gt; '2010', :month =&gt; '02'} end end </code></pre> <p>Results in <code>can't convert Hash into String</code> error.</p> <p>This seems to be ignored:</p> <pre><code>def to_param '2010/02/my-first-post' end </code></pre> <p>as it results in error: <code>post_url failed to generate from {:action=&gt;"show", :year=&gt;#&lt;Post id: 1, title: (...)</code> (it wrongly assigns @post object to the :year key). I'm kind of clueless at how to hack it.</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