rails URL 重写使用

rails URL rewriting using

下面如何重写URL

127.0.0.1:3000/article/index?type=1

作为

127.0.0.1:3000/article/category/brand

其中类型 1 是具有名牌的类别。

是否可以使用 rails?

route.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到这条路线

<%= link_to category.name, {:controller => "article", :action => "index", :type => category.id }%>

Rails 不提供您想要立即实现的目标。在这里,我给你一些建议,让你到达你想去的地方。

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

因此您的配置没有问题,但不是一个好的做法。了解更多 here

  1. models/article.rb - 保持原样
  2. 使用https://github.com/norman/friendly_id Gem. Follow usage guide https://github.com/norman/friendly_id#usage安装配置。

  3. models/category.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

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