私のウェブサイトに次のようなURLを設定したいのですが。
example.com/2010/02/my-first-post
フィールド(「my-first-post」)とフィールド(URLの年と月の部分を差し引く)を持つPost
モデルがあります。slug
published_on
Post
モデルをRESTfulにしたいので、たとえば、url_for(@post)
前述のURLを生成する必要があります。
これを行う方法はありますか?オプションをオーバーライドto_param
して設定する必要があることはわかっていますが、すべてを機能させることはできません。map.resources :posts
:requirements
私はそれをほぼ完了しました、私はそこに90%います。resource_hacksプラグインを使用して、これを実現できます。
map.resources :posts, :member_path => '/:year/:month/:slug',
:member_path_requirements => {:year => /[\d]{4}/, :month => /[\d]{2}/, :slug => /[a-z0-9\-]+/}
rake routes
(...)
post GET /:year/:month/:slug(.:format) {:controller=>"posts", :action=>"show"}
とビューで:
<%= link_to 'post', post_path(:slug => @post.slug, :year => '2010', :month => '02') %>
example.com/2010/02/my-first-post
適切なリンクを生成します。
私もこれを機能させたいです:
<%= link_to 'post', post_path(@post) %>
to_param
ただし、モデルのメソッドをオーバーライドする必要があります。私が望むようにではなく、それto_param
が戻らなければならないという事実を除いて、かなり簡単なはずです。String
Hash
class Post < ActiveRecord::Base
def to_param
{:slug => 'my-first-post', :year => '2010', :month => '02'}
end
end
エラーが発生しcan't convert Hash into String
ます。
これは無視されているようです:
def to_param
'2010/02/my-first-post'
end
エラーが発生するため: post_url failed to generate from {:action=>"show", :year=>#<Post id: 1, title: (...)
(@postオブジェクトを:yearキーに誤って割り当てます)。私はそれをハックする方法についてちょっと無知です。