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
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.
path is relative while url is absolute.
This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.
Considering the same case, the two terms can be differentiated in a simple way as :member is used when a route has a unique field :id or :slug and :collection is used when there is no unique field required in the route.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With