[英]params to find by name instead of id
I want the url structure to be 'actors/joe-blogs' instead of 'actors/1' but with the id out of the url I cant get params to find by name instead of find by id. 我希望url结构是“ actors / joe-blogs”,而不是“ actors / 1”,但是在id不在url中的情况下,我无法通过名称而不是通过id查找来获取参数。
I have the following route 我有以下路线
get 'actors/:name' => 'actors#show'
actors table 演员表
| id | name |
------------------
| 1 | Joe Blogs |
The url /actors/joe-blogs works fine but finding params by name instead of id doesn't work. url / actors / joe-blogs可以正常工作,但是按名称而不是id查找params无效。
actors controller: 演员控制器:
def show
@actor = Actor.find(params[:name])
end
Finding by params name looks for the actor with {"name"=>"joe-blogs"}
instead of looking for the actor with {"name"=>"Joe Blogs"}
通过参数名称查找使用
{"name"=>"joe-blogs"}
的演员,而不是使用{"name"=>"Joe Blogs"}
的演员
How can I get params to work so it grabs {"name"=>"Joe Blogs"}
? 我怎样才能使params起作用,以便它抓住
{"name"=>"Joe Blogs"}
? without the '-' in-between the name? 名称之间没有'-'吗?
You should use find_by
instead of find
. 您应该使用
find_by
而不是find
。
def show
@actor = Actor.find_by(name: params[:name])
end
You'll be best using friendly_id
, which will fix all of this functionality for you. 最好使用
friendly_id
,它将为您修复所有此功能。 You won't have to change anything except adding a slug
column to your datatable: 除了向数据表添加一个
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)
This should set up all your Author
records to have a slug
, which will allow you to use the following: 这应该将所有
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.