Rails 3.2 дружественная маршрутизация URL по дате
Я хочу реализовать приложение блог \ новости с возможностью:
show all posts at root:example.com/
show all posts answering some year: example.com/2012/
show all posts answering some year and month: example.com/2012/07/
show some post by its date and slug: 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
действие и просто получить сообщение от пули вshow
действие (проверка, является ли дата corect, является опцией):
# 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.
Но проблема в том,strange things keep happenning для меня как новичка в рельсах
When I go to localhost/
, the app breaks and says that it had invoked show
action but first object in database had been recieved as :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">}
When I go to localhost/posts/2012/07/cut-test
same thing happens:
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 без даты и подобных, но не полезных вопросов.