如何使用friendly_id制作带有范围的漂亮网址?

时间:2016-01-12 20:39:42

标签: ruby-on-rails ruby-on-rails-4 friendly-id

我正在建立一个博客,我希望我的类别拥有漂亮的网址 blog/art/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

-

= 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)}/

查看

Article.by_category(params[:category])

控制器

@CreatedBy Employee employee

2 个答案:

答案 0 :(得分:1)

此任务不需要friendly_id

在您的路线中添加以下内容:

  get 'blog/:category', to: 'articles#index', as: "category"

然后

 link_to category, category_path(category)

http://guides.rubyonrails.org/routing.html

答案 1 :(得分:1)

您只需要friendly_id根据类别标题创建slu ..如果你想在类别范围内使slug成为唯一的,你可以使用特殊的friendly_id module来解决这个问题。

要在网址中进行漂亮的嵌套,您可以在路线中执行以下操作:

get 'blog/:category', to: 'articles#index', as: "category"

你的文章控制器里有这样的东西:

class ArticlesController < ApplicationController
  def index
    @category = Category.friendly.find(params[:category])
    @articles = @category.articles
    respond_to do |format|
      # and so on...
    end
  end
end

您的观点中有类似的内容:

link_to category.title, category_url(category)