使用 :name 而不是 :id url 参数的 Rails 路由 [英] Rails routes with :name instead of :id url parameters

查看:26
本文介绍了使用 :name 而不是 :id url 参数的 Rails 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为公司"的控制器,而不是每个公司的 url 都用 :id 表示,我想让 url 使用它们的 :name,例如:url/company/microsoft 而不是 url/company/3.

I have a controller named 'companies' and rather than the urls for each company being denoted with an :id I'd like to have the url use their :name such as: url/company/microsoft instead of url/company/3.

在我的控制器中,我假设我会有

In my controller I assumed I would have

 def show
   @company = Company.find(params[:name])
 end

因为 url 中不会有任何其他参数,所以我希望 Rails 能够理解 :name 引用了我公司模型中的 :name 列.我认为这里的魔法会在路线中,但我在这一点上被卡住了.

Since there won't be any other parameter in the url I was hoping rails would understand that :name referenced the :name column in my Company model. I assume the magic here would be in the route but am stuck at this point.

推荐答案

params

最重要的是,您正在寻找错误的解决方案 - params 哈希键相当无关紧要,您需要能够更有效地使用其中包含的数据.

The bottom line is you're looking at the wrong solution - the params hash keys are rather irrelevant, you need to be able to use the data contained inside them more effectively.

您的路线将被构建为:

#config/routes.rb
resources :controller #-> domain.com/controller/:id

这意味着如果您请求此路由:domain.com/controller/your_resourceparams[:id] 哈希值将为 your_resource> (不管它叫params[:name] 还是params[:id])

This means if you request this route: domain.com/controller/your_resource, the params[:id] hash value will be your_resource (doesn't matter if it's called params[:name] or params[:id])

--

friendly_id

你有几个推荐 friendly_id 的答案的原因是因为它覆盖了 ActiveRecordfind 方法,允许你使用 slug 在您的查询中:

The reason you have several answers recommending friendly_id is because this overrides the find method of ActiveRecord, allowing you to use a slug in your query:

#app/models/model.rb
Class Model < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: [:slugged, :finders]
end

这允许您这样做:

#app/controllers/your_controller.rb
def show
    @model = Model.find params[:id] #-> this can be the "name" of your record, or "id"
end

这篇关于使用 :name 而不是 :id url 参数的 Rails 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆