按名称而不是 id 查找的参数

params to find by name instead of id

我希望 url 结构是 'actors/joe-blogs' 而不是 'actors/1' 但是由于 id 不在 url 我无法通过名称而不是通过名称查找参数按id查找。

我有以下路线

get 'actors/:name' => 'actors#show'

演员table

| id |   name    |
------------------
| 1  | Joe Blogs |

url /actors/joe-blogs 工作正常,但按名称而不是 id 查找参数不起作用。

演员控制器:

    def show
       @actor = Actor.find(params[:name])
    end

Finding by params name 查找具有 {"name"=>"joe-blogs"} 的演员,而不是查找具有 {"name"=>"Joe Blogs"}

的演员

我怎样才能让参数起作用以便它抓取 {"name"=>"Joe Blogs"}?名字中间没有“-”?

您应该使用 find_by 而不是 find

def show
  @actor = Actor.find_by(name: params[:name])
end

您最好使用 friendly_id,它将为您修复所有这些功能。除了向数据表添加 slug 列外,您无需更改任何内容:

#Gemfile
gem 'friendly_id', '~> 5.1'

$ rails generate friendly_id
$ rails generate scaffold actor name:string slug:string:uniq
$ rake db:migrate

#app/models/actor.rb
class Actor < ActiveRecord::Base
   extend FriendlyID
   friendly_id :name, use: [:slugged, :finders]
end

$ rails c
$ Actor.find_each(&:save)

这应该将所有 Author 记录设置为具有 slug,这将允许您使用以下内容:

#config/routes.rb
resources :actors #-> no change required

#app/controllers/actors_controller.rb
class AuthorsController < ApplicationController
   def show
      @author = Actor.find params[:id] #-> will automatically populate with slug
   end
end