Rails routes with :name instead of :id url parameters

前端 未结 7 1980
渐次进展
渐次进展 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 13:59

    Honestly, I would just overwrite the to_param in the Model. This will allow company_path helpers to work correctly.

    Note: I would create a separate slug column for complex name, but that's just me. This is the simple case.

    class Company < ActiveRecord::Base
      def to_param
        name
      end
    end
    

    Then change my routes param for readability.

    # The param option may only be in Rails 4+,
    # if so just use params[:id] in the controller
    resources :companies, param: :name
    

    Finally in my Controller I need to look it up the right way.

    class CompaniesController < ApplicationController
      def show
        # Rails 4.0+
        @company = Company.find_by(name: params[:name])
        # Rails < 4.0
        @company = Company.find_by_name(params[:name])
      end
    end
    

提交回复
热议问题