如何隐藏 url 中的 id (ruby on Rails)

发布于 2024-12-06 15:49:41 字数 335 浏览 0 评论 0原文

我有一个用 Ruby On Rails 制作的网络应用程序。现在,当我想显示对象时,我必须访问以下页面: http://mywebapp.com/object/第1234章 第1234章

我想对该对象 ID 进行编码并得到以下结果: http://mywebapp.com/object/5k(这只是一个例子)。

怎么办呢?

非常感谢,
马丁

I have a web app made with Ruby On Rails. For now when I want to display an object I have to access the following page: http://mywebapp.com/object/1234 with 1234 the id of the object.

I would like to encode that object id and have the following result: http://mywebapp.com/object/5k (it is just an example).

How can it be done?

Many thanks,
Martin

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉生梦死 2024-12-13 15:49:42

所有这些转换方法都是可逆的,所以恕我直言,如果您的对象有一些名称或标题或其他什么,那么最好的方法是添加一个slug。
在这种情况下,向您的对象添加一个新属性 :slug,让我们从模型上的对象名称(或其他内容)自动生成它的值:

class MyObject

  validates_format_of :slug, :with => /\A[a-z\-0-9]*\Z/
  before_validation :generate_slug, :on => :create    

  def generate_slug
    if self.slug.blank?
      slug = self.name.mb_chars.downcase.normalize(:kd).to_s.gsub(/-/, " ").squeeze(" ")
      slug = slug.gsub(/\s/, "-").gsub(/[^a-z\-0-9]/, "")

      current = 1
      self.slug = slug
      while true
        conflicts = MyObject.where("slug = ?", self.slug).count
        if conflicts != 0
          self.slug = "#{slug}-#{current}"
          current += 1
        else
          break
        end
      end
    end
  end
end

然后 URL 可以是 http://mywebapp.com/object/my_object_slug,因为在操作中您可以通过此 slug 找到对象:

class MyObjectController

  def some_action
    my_object = MyObject.find_by_slug(params[:slug])

    ...

  end
end

不要忘记修改 paths.rb:

match "object/:slug", :to => "my_objects#some_action"

All these converting methods are reversible, so IMHO if your object has some name or title or whatever, then the best way is adding a slug.
In such case add a new attribute :slug to your object, let automatically generate it's value from object name (or something else) on the model:

class MyObject

  validates_format_of :slug, :with => /\A[a-z\-0-9]*\Z/
  before_validation :generate_slug, :on => :create    

  def generate_slug
    if self.slug.blank?
      slug = self.name.mb_chars.downcase.normalize(:kd).to_s.gsub(/-/, " ").squeeze(" ")
      slug = slug.gsub(/\s/, "-").gsub(/[^a-z\-0-9]/, "")

      current = 1
      self.slug = slug
      while true
        conflicts = MyObject.where("slug = ?", self.slug).count
        if conflicts != 0
          self.slug = "#{slug}-#{current}"
          current += 1
        else
          break
        end
      end
    end
  end
end

then the URL can be http://mywebapp.com/object/my_object_slug, because in action you find the object via this slug:

class MyObjectController

  def some_action
    my_object = MyObject.find_by_slug(params[:slug])

    ...

  end
end

Don't forget modify routes.rb:

match "object/:slug", :to => "my_objects#some_action"
汐鸠 2024-12-13 15:49:42

您可能可以使用 Base64 编码来做到这一点(尽管如果您确实想对内部 id 保密,那么有人可能会猜测您正在使用 Base64 编码并轻松确定 id)。

你的控制器需要看起来有点像这样

class ThingsController < ApplicationController
  require 'base64'

  def show
    @thing = Thing.find Base64.urlsafe_decode64(params[:id])
  end

  def edit
    @thing = Thing.find Base64.urlsafe_decode64(params[:id])
  end

  #These are just a couple of very simple example actions

end

现在,实际上对你的 URL 进行编码会有点棘手 - 我会研究它,因为这似乎是一个有趣的问题(但我不会做出任何承诺)。

  • 编辑 -

一些阅读表明 ActionView 使用 url_for 中的 to_param 方法来获取对象的 id。我们可以在模型本身中重写它来对 id 进行编码,就像

class Thing < ActiveRecord::Base

  def to_param
    Base64.urlsafe_encode64 self.id.to_s
  end

end

我在这里写的所有内容都是推测的。我之前没有这样做过,也没有测试过代码,所以我不能保证它是否有效或者是否会引入不可预见的问题。我很想听听你进展如何。

You could probably do this with Base64 encoding (although if you're really trying to keep the internal id secret someone could probably guess you're using Base64 encoding and easily determine the id).

Your controller would need to look a bit like this

class ThingsController < ApplicationController
  require 'base64'

  def show
    @thing = Thing.find Base64.urlsafe_decode64(params[:id])
  end

  def edit
    @thing = Thing.find Base64.urlsafe_decode64(params[:id])
  end

  #These are just a couple of very simple example actions

end

Now actually encoding your URLs is going to be a little bit trickier - I'll look into it as it seems like an interesting problem (but I'm not making any promises).

  • Edit -

A bit of reading reveals that ActionView uses the to_param method in url_for to get the id of an object. We can override this in the model itself to encode the id like so

class Thing < ActiveRecord::Base

  def to_param
    Base64.urlsafe_encode64 self.id.to_s
  end

end

Everything I've written here is conjectural. I haven't done this before or tested the code so I can't give any guarantee as to whether it will work or whether it will introduce unforeseen problems. I'd be very interested to hear how you go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文