Rails routes with :name instead of :id url parameters

前端 未结 7 1977
渐次进展
渐次进展 2020-12-05 13:05

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/comp

7条回答
  •  隐瞒了意图╮
    2020-12-05 14:03

    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"
    

提交回复
热议问题