In Rails 4 is there another cleaner way to achieve routes, such as:
/blog/2014/8/blog-post-title
/blog/2014/8
/blog/2014
/blog/2014/8/tags/tag-1,tag-2/page/4
/blog/new OR /blog_posts/new
I've tried the following using FriendlyId
(as well as acts-as-taggable
for tag param and kaminari
for page param):
blog_post.rb
extend FriendlyId
friendly_id :slug_candidates, use: [:slugged, :finders]
def to_param
"#{year}/#{month}/#{title.parameterize}"
end
def slug_candidates
[
:title,
[:title, :month, :year]
]
end
def year
created_at.localtime.year
end
def month
created_at.localtime.month
end
routes.rb
match '/blog_posts/new', to: 'blog_posts#new', via: 'get'
match '/blog_posts/:id/edit', to: 'blog_posts#edit', via: 'get'
match '/blog_posts/:id/edit', to: 'blog_posts#update', via: 'post'
match '/blog_posts/:id/delete', to: 'blog_posts#destroy', via: 'destroy'
match '/blog(/page/:page)(/tags/:tags)(/:year)(/:month)', to: 'blog_posts#index', via: 'get'
match '/blog/:year/:month/:title', to: 'blog_posts#show', via: 'get'
resources 'blog', controller: :blog_posts, as: :blog_posts
Used resources so can have path and url helpers as normal.
This works (minus update yet), but feels very ugly. Is there a better way?
/blog_posts/action
instead of/blog/action
, otherwise it will interpret the action as a year parameter e.g.year="new"
. Maybe there is another approach just in respect to those route definitions? – TODOMyName