Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes with :name instead of :id url parameters

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.

like image 672
dscher Avatar asked Jun 15 '14 03:06

dscher


People also ask

What is the difference between path and URL in Rails?

path is relative while url is absolute.

What is namespace routes in Rails?

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.

What is the difference between member and collection in Rails route?

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.


1 Answers

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" 
like image 88
Matrix Avatar answered Sep 17 '22 13:09

Matrix