如何使用 friendly_id 使用范围制作漂亮的 url?
How to make pretty url's with scopes using friendly_id?
我正在建立一个博客,我希望我的类别有漂亮的 URL 喜欢
blog/music
、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])
您不需要friendly_id
完成此任务
在你的路线中添加这样的东西:
get 'blog/:category', to: 'articles#index', as: "category"
然后
link_to category, category_path(category)
您 friendly_id
只需要根据类别标题创建 slug。如果你想让 slug 在类别范围内独一无二,你可以使用特殊 friendly_id module 来解决这个问题。
为了在 url 中进行漂亮的嵌套,你可以在你的路由中做这样的事情:
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)
我正在建立一个博客,我希望我的类别有漂亮的 URL 喜欢
blog/music
、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])
您不需要friendly_id
完成此任务
在你的路线中添加这样的东西:
get 'blog/:category', to: 'articles#index', as: "category"
然后
link_to category, category_path(category)
您 friendly_id
只需要根据类别标题创建 slug。如果你想让 slug 在类别范围内独一无二,你可以使用特殊 friendly_id module 来解决这个问题。
为了在 url 中进行漂亮的嵌套,你可以在你的路由中做这样的事情:
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)