[英]Custom url_for for non rolling ids
Right now if I create a URL for a model show action I simply call: 现在,如果我为模型展示操作创建URL,则只需调用:
link_to model_instance
which creates something like this the when model is User and the id is 1: 这会在模型为User且id为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. 我喜欢自定义行为,而不必遍历代码库中为此类模型生成URL的所有实例。 The motivation behind the change is avoiding rolling id's in the URL that lets anybody discover other entries by simply increasing the id.
进行更改的动机是避免在网址中滚动ID,该ID允许任何人通过简单地增加ID即可发现其他条目。 So something like
所以像
/user/88x11bc1200
Is there a place where I can simply override how a URL for selected models are generated? 是否可以简单地覆盖如何为选定模型生成URL? I am using RoR 4.x
我正在使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.