How to rename the default identifier param “id” in Rails' map.resources()?

后端 未结 2 2074
谎友^
谎友^ 2021-02-02 00:53

I like all the default routes that are generated by Rail\'s map.resources. But, there are cases where I would like to use a non-numeric identifier in my routes.

2条回答
  •  我在风中等你
    2021-02-02 01:26

    You can change the default of using the ID in URLs by overriding to_param in your model. e.g.

    class User < ActiveRecord::Base
      def to_param
        login
      end
    end
    
    user_articles_path(@user) => "/users/:login/articles"
    

    The only other change you'll need to make is to find users by login rather than by ID in your controllers.

提交回复
热议问题