次の機能を備えた blog\news アプリケーションを実装したいと考えています。
- ルートのすべての投稿を表示:
example.com/
- ある年に回答したすべての投稿を表示:
example.com/2012/
- 特定の年と月に回答するすべての投稿を表示:
example.com/2012/07/
- 日付とスラッグでいくつかの投稿を表示します。
example.com/2012/07/slug-of-the-post
routes.rb
だから私はファイルのモックアップを作成しました:
# GET /?page=1
root :to => "posts#index"
match "/posts" => redirect("/")
match "/posts/" => redirect("/")
# Get /posts/2012/?page=1
match "/posts/:year", :to => "posts#index",
:constraints => { :year => /\d{4}/ }
# Get /posts/2012/07/?page=1
match "/posts/:year/:month", :to => "posts#index",
:constraints => { :year => /\d{4}/, :month => /\d{1,2}/ }
# Get /posts/2012/07/slug-of-the-post
match "/posts/:year/:month/:slug", :to => "posts#show", :as => :post,
:constraints => { :year => /\d{4}/, :month => /\d{1,2}/, :slug => /[a-z0-9\-]+/ }
だから私はアクションでparamsを操作し、index
アクションでスラッグごとにポストを取得するshow
必要があります(日付が正しいかどうかをチェックすることはオプションです):
# GET /posts?page=1
def index
#render :text => "posts#index<br/><br/>#{params.to_s}"
@posts = Post.order('created_at DESC').page(params[:page])
# sould be more complicated in future
end
# GET /posts/2012/07/19/slug
def show
#render :text => "posts#show<br/><br/>#{params.to_s}"
@post = Post.find_by_slug(params[:slug])
end
to_param
また、モデルに実装する必要があります:
def to_param
"#{created_at.year}/#{created_at.month}/#{slug}"
end
これは、一晩中 api/guides/SO を検索して学んだことのすべてです。
しかし、問題は、レールを初めて使用する私にとって奇妙なことが起こり続けることです。
に移動する
localhost/
と、アプリが壊れて、show
アクションを呼び出したが、データベース内の最初のオブジェクトが :year として受信されたと表示されます (sic!):No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: 12, slug: "*", title: "*", content: "*", created_at: "2012-07-19 15:25:38", updated_at: "2012-07-19 15:25:38">}
私が行くと
localhost/posts/2012/07/cut-test
同じことが起こります:No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: 12, slug: "*", title: "*", content: "*", created_at: "2012-07-19 15:25:38", updated_at: "2012-07-19 15:25:38">}
私が作ったことのない非常に簡単なものがあるように感じますが、それが何であるかを見つけることができません。
とにかく、この投稿は解決時に役立ちます。日付のない URL のスラッグだけに対する解決策と、類似しているが有用ではない質問に対する解決策しかないためです。