Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This might be helpful. You can define a <a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000661" rel="nofollow noreferrer"><code>default_url_options</code></a> method in your <code>ApplicationController</code> that receives a Hash of options that were passed to the url helper and returns a Hash of additional options that you want to use for those urls.</p> <p>If a post is given as a parameter to <code>post_path</code>, it will be assigned to the first (unnassigned) parameter of the route. Haven't tested it, but it might work:</p> <pre><code>def default_url_options(options = {}) if options[:controller] == "posts" &amp;&amp; options[:year].is_a?Post post = options[:year] { :year =&gt; post.created_at.year, :month =&gt; post.created_at.month, :slug =&gt; post.slug } else {} end end </code></pre> <p>I'm in the similar situation, where a post has a language parameter and slug parameter. Writing <code>post_path(@post)</code> sends this hash to the <code>default_url_options</code> method:</p> <pre><code>{:language=&gt;#&lt;Post id: 1, ...&gt;, :controller=&gt;"posts", :action=&gt;"show"} </code></pre> <p>UPDATE: There's a problem that you can't override url parameters from that method. The parameters passed to the url helper take precedence. So you could do something like:</p> <pre><code>post_path(:slug =&gt; @post) </code></pre> <p>and:</p> <pre><code>def default_url_options(options = {}) if options[:controller] == "posts" &amp;&amp; options[:slug].is_a?Post { :year =&gt; options[:slug].created_at.year, :month =&gt; options[:slug].created_at.month } else {} end end </code></pre> <p>This would work if <code>Post.to_param</code> returned the slug. You would only need to add the year and month to the hash.</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