首页 > 解决方案 > 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 }%>

标签: ruby-on-railsruby-on-rails-5rails-routing

解决方案


Rails 没有提供您想要实现的开箱即用的功能。在这里,我给你一些建议,让你到达你想去的地方。

  1. 路线.rb
get "articles/category/:id" => "articles#index", as: "articles_by_category"

因此,您的配置没有问题,但不是一个好习惯。在此处了解更多信息

  1. models/article.rb - 保持原样
  2. 使用https://github.com/norman/friendly_id宝石。按照使用指南https://github.com/norman/friendly_id#usage安装和配置它。

  3. 模型/类别.rb

class Category < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged

  has_many :articles
end
  1. <%= link_to category.name, articles_by_category_path(category.id) %>
    
  2. article_controller.rb

def index
  @articles = Category.friendly.find(params[:id]).articles
end

PS这里的假设是给定类别会有多篇文章。


推荐阅读