繁体   English   中英

非滚动ID的自定义url_for

[英]Custom url_for for non rolling ids

现在,如果我为模型展示操作创建URL,则只需调用:

link_to model_instance

这会在模型为User且id为1时创建类似这样的内容:

/user/1

我喜欢自定义行为,而不必遍历代码库中为此类模型生成URL的所有实例。 进行更改的动机是避免在网址中滚动ID,该ID允许任何人通过简单地增加ID即可发现其他条目。 所以像

/user/88x11bc1200

是否可以简单地覆盖如何为选定模型生成URL? 我正在使用RoR 4.x

实际上,您必须在两个地方进行更新。

在模型中

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

在控制器中

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.

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