I'm creating a blog for myself with Rails 3.2.5, and am trying to handle tags
and categories
properly. I want to allow the user to click on a link_to
with the tag name that brings them to other entries with the same tag and have the URL be 'root.com/tag/selected-tag'
. For categories I'd like to have the same thing with the URL being 'root.com/category/selected-category'
. I've already started on this and am using acts_as_taggable_on
for tagging and a simple text input
for the category (will become a select input
when I decide what categories I want).
How would I go about handling this? I've tried creating a controller for tags
and categories
, each with only an index
action. For 'tags#index'
I have:
@entries = Entry.order('created_at desc').tagged_with(params[:format]).paginate(:page => params[:page], :per_page => 10)
and for each tag
's link I have:
= link_to tag, tag_path(tag)
For some reason the tag
is being passed as the :format
, that's why I've got tagged_with(params[:format])
.
I have 'categories#index'
defined as:
@entries = Entry.order('created_at desc').where(:category => params[:format]).paginate(:page => params[:page], :per_page => 10)
and the category
's link is:
- entry.tag_list.each do |tag|
= link_to tag, tag_path(tag)
Since the tags
and category
are being passed as the :format
the URL's are appearing as 'root.com/tag.selected-tag'
and 'root.com/category.selected-category'
.
How would I go about handling tags
and categories
properly to achieve getting the URL's to appear as 'root.com/tag/selected-tag'
and 'root.com/category/selected-category'
?
The below will probably do what you want:
In your routes:
match 'tag/:tag' => 'tags#index', :as => :tag
Then, when someone visits example.com/tag/some-tag-here
, you can then access the tag within your controller through:
params[:tag]
you can link to your route by doing:
link_to tag, tag_path(:tag => tag)
An analogous solution should work for categories as well.