簡體   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