ruby-on-rails - rails URL重写使用
问题描述
如何重写以下网址
127.0.0.1:3000/article/index?type=1
作为
127.0.0.1:3000/article/category/brand
其中类型 1 是具有名牌的类别。
可以使用导轨吗?
路由.rb
get "article/index"
article_controller.rb
def index
@article = Article.find(params[:type])
end
article.rb //模型
class Article < ApplicationRecord
belongs_to :category
end
链接到这条路线
<%= link_to category.name, {:controller => "article", :action => "index", :type => category.id }%>
解决方案
Rails 没有提供您想要实现的开箱即用的功能。在这里,我给你一些建议,让你到达你想去的地方。
- 路线.rb
get "articles/category/:id" => "articles#index", as: "articles_by_category"
因此,您的配置没有问题,但不是一个好习惯。在此处了解更多信息
- models/article.rb - 保持原样
使用https://github.com/norman/friendly_id宝石。按照使用指南https://github.com/norman/friendly_id#usage安装和配置它。
模型/类别.rb
class Category < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
has_many :articles
end
<%= link_to category.name, articles_by_category_path(category.id) %>
article_controller.rb
def index
@articles = Category.friendly.find(params[:id]).articles
end
PS这里的假设是给定类别会有多篇文章。
推荐阅读
- android - Kotlin - 如何创建类似于 TextView.setText(String) 的类成员函数,可以作为 TextView.text = "" 调用
- angular - Angular 4 Typescript - 构造随后 7 天的日期数组
- sql - 我想透视表
- angular - 使用 Angular 4 / ionic 在模板中显示 const
- c++ - 如何在C++中创建一个n行5列的数组,但是n值在变化
- oracle - SQL避免在select语句中两次调用相同的函数
- python - Python - 删除 datafeame 单元格中的重复项
- spring - SpringBoot 不扫描命名包
- google-cloud-dataflow - 不可调试的数据流异常
- git - 将 Gitlab 分支迁移到另一个项目的最快方法