这是一个保持数字的 gem,不需要数据库迁移,也不需要更改路由:https://github.com/namick/obfuscate_id
我发现这个 gem 不能与其他一些 gem 协同工作,尤其是 paper_trail。这是因为它替换了 find 方法的方式,而 paper_trail 导致 find 使用实际记录 id 被调用。
所以我一直在使用 gem 的“scatter_swap”功能,但没有使用它的其余部分。这是模型:
require 'obfuscate_id/scatter_swap'
class Page < ActiveRecord::Base
# This is a random number that, if changed, will invalidate all existing URLs. Don't change it!
@@obfuscate_spin = # random number here, which is essentially the encryption key
##
# Generate URL parameter to be used in the URL as the "id"
def to_param
# Use the obfuscate_id gem's class to "spin" the id into something obfuscated
spun_id = ScatterSwap.hash(self.id, @@obfuscate_spin)
# Throw any additional attributes in here that are to be included in the URL.
"#{spun_id} #{name}".parameterize
end
def self.find_by_slug!(slug)
spun_id = slug[/^[0-9]+/]
begin
find_by_id! ScatterSwap.reverse_hash(spun_id, @@obfuscate_spin)
rescue ActiveRecord::RecordNotFound => e
raise ActiveRecord::RecordNotFound, "Couldn't find matching Page."
end
end
end
在控制器中:
class PagesController < InheritedResources::Base
# Find the page using its URL slug
before_filter :find_page, except: [:index, :create, :new]
def find_page
@page = Page.find_by_slug! params[:id]
# If the URL doesn't match exactly, and this is a GET.
# We'll redirect to the new, correct URL, but if this is a non-GET, let's let them finish their request instead.
if params[:id] != @page.to_param && request.get?
redirect_to url_for({ id: @page.to_param }), status: 301
end
end
end
作为在那里发生的重定向的替代方法,您可以简单地在页面中包含一个规范的 URL。重定向存在忽略 URL 中任何查询参数的错误。这对我的项目来说不是问题,因为我没有任何问题。但是规范的 URL 会更好。