Rails routes with :name instead of :id url parameters
Good answer with Rails 4.0+ :
resources :companies, param: :name
optionally you can use only:
or except:
list to specify routes
and if you want to construct a URL, you can override ActiveRecord::Base#to_param of a related model:
class Video < ApplicationRecord
def to_param
identifier
end
# or
alias_method :to_param, :identifier
end
video = Video.find_by(identifier: "Roman-Holiday")
edit_videos_path(video) # => "/videos/Roman-Holiday"
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.
Your routes will be constructed as:
#config/routes.rb
resources :controller #-> domain.com/controller/: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
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
This allows you to do this:
#app/controllers/your_controller.rb
def show
@model = Model.find params[:id] #-> this can be the "name" of your record, or "id"
end