简体   繁体   中英

Custom url_for for non rolling ids

Right now if I create a URL for a model show action I simply call:

link_to model_instance

which creates something like this the when model is User and the id is 1:

/user/1

I like to customize that behavior without having to go through all instances in the codebase where a URL for such a model is generated. The motivation behind the change is avoiding rolling id's in the URL that lets anybody discover other entries by simply increasing the id. So something like

/user/88x11bc1200

Is there a place where I can simply override how a URL for selected models are generated? I am using RoR 4.x

There are essentially two places you'll have to update.

In the model

class User < ActiveRecord::Base
  # Override the to_param method
  def to_param
    # Whatever your field is called
    non_rolling_id
  end
end

In the controller

class UsersController < ApplicationController
  def show
    # Can't use `find` anymore, but will still come over as `id`
    @user = User.find_by_non_rolling_id(params[:id])
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM