Reputation: 2520
I'm building a blog and I want my categories to have beautiful URL's like
blog/music
, blog/art
, etc.
So far, I've managed to make them look like this
/blog?category=music
class Article < ActiveRecord::Base
belongs_to :category
extend FriendlyId
friendly_id :title, use: :slugged
scope :by_category, -> (slug) { joins(:category).where('categories.slug = ?', slug) if slug }
end
-
class Category < ActiveRecord::Base
has_many :articles
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
end
view
= active_link_to category.name, articles_path(category: category.slug), remote: true,
class_active: 'active', class_inactive: 'inactive', wrap_tag: :dd, active: /#{Regexp.escape(category=category.slug)}/
controller
Article.by_category(params[:category])
Upvotes: 0
Views: 238
Reputation: 562
You need friendly_id
only to create slugs based on title of the category. If you want to make slug unique in scope of category you can use special friendly_id module to solve this problem.
To make nice nesting in url you can do something like this in your routes:
get 'blog/:category', to: 'articles#index', as: "category"
Something like this in your articles controller:
class ArticlesController < ApplicationController
def index
@category = Category.friendly.find(params[:category])
@articles = @category.articles
respond_to do |format|
# and so on...
end
end
end
And something like this in your views:
link_to category.title, category_url(category)
Upvotes: 1
Reputation: 2470
You don't need friendly_id
for this task
add something like this to your routes:
get 'blog/:category', to: 'articles#index', as: "category"
and then
link_to category, category_path(category)
http://guides.rubyonrails.org/routing.html
Upvotes: 1