Reputation: 1855
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.
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.
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"}
How can I get params to work so it grabs {"name"=>"Joe Blogs"}
? without the '-' in-between the name?
Upvotes: 3
Views: 3745
Reputation: 76774
You'll be best using friendly_id
, which will fix all of this functionality for you. You won't have to change anything except adding a slug
column to your datatable:
#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:
#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
Upvotes: 0
Reputation: 33542
You should use find_by
instead of find
.
def show
@actor = Actor.find_by(name: params[:name])
end
Upvotes: 6