简体   繁体   English

rails sha1哈希到对象的路由?

[英]rails sha1 hash for route to object?

I want to my controller in my app to not just respond to the id of the object sent from it's route, but actually a sha1 hash, i've generated using Digest::SHA1.hexdigest . 我希望我的应用程序中的控制器不仅响应从其路由发送的对象的ID,而且实际上响应我使用Digest::SHA1.hexdigest生成的sha1哈希。

So instead of: 所以代替:

/client/invoice/1

I want the url to be something like: 我希望网址是这样的:

/client/invoice/0beec7b5ea3f0fdbc95d0

Changing the URL for an object in Rails generally involves two things: 在Rails中更改对象的URL通常涉及两件事:

First, change relevant controller actions to use a finder that works the way you want it to. 首先,更改相关的控制器动作,以使用可以按照您希望的方式工作的查找器。 In your case you probably want to write a custom finder in your Invoice model, like: 在您的情况下,您可能希望在Invoice模型中编写一个自定义查找器,例如:

def self.find_by_id_or_sha1(id)
  Invoice.find_by_id(id) || Invoice.find_by_sha1(id)
end

and then use Invoice.find_by_id_or_sha1(params[:id]) in your controller actions (show, edit, update, destroy). 然后在您的控制器操作(显示,编辑,更新,销毁)中使用Invoice.find_by_id_or_sha1(params[:id]) )。

Second, change generated URLs to follow your new design (if desired). 其次,更改生成的URL以遵循您的新设计(如果需要)。 So, if you want link_to("Jan 1, 2010", @invoice) to go to /client/invoice/0beec7b5ea3f0fdbc95d0 , override the default to_param method in your Invoice model. 因此,如果您希望link_to("Jan 1, 2010", @invoice)转到/client/invoice/0beec7b5ea3f0fdbc95d0 ,请在Invoice模型中覆盖默认的to_param方法。 For example: 例如:

def to_param
  sha1
end

(That assumes your invoice's SHA1 hash is stored in the sha1 attribute.) (假定发票的SHA1哈希存储在sha1属性中。)

Invoice.first(:conditions=>["SHA(id) = ?",params[:id]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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