【问题标题】:rails URL rewriting usingrails URL重写使用
【发布时间】:2020-03-31 07:08:44
【问题描述】:

如何改写以下网址

127.0.0.1:3000/article/index?type=1

作为

127.0.0.1:3000/article/category/brand

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

是否可以使用rails?

路由.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 }%>

【问题讨论】:

  • 分享您的 routes.rb、文章和类别模型,以及查看代码。
  • 请检查上面的更新代码

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


【解决方案1】:

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宝石。按照使用指南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

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

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多