我想实现 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\-]+/ }
所以我应该在index
行动中使用参数,并通过行动中的 slug 来发布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 中通宵搜索所学到的全部内容。
但问题是奇怪的事情不断发生,因为我刚接触 Rails:
当我去时
localhost/
,应用程序中断并说它已调用show
操作但数据库中的第一个对象已被接收为:年(原文如此!):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 中没有日期的 slug 和类似但没有用的问题的解决方案。