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 Di开发者_如何学Gogest::SHA1.hexdigest
.
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:
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:
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).
Second, change generated URLs to follow your new design (if desired). 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. For example:
def to_param
sha1
end
(That assumes your invoice's SHA1 hash is stored in the sha1 attribute.)
Invoice.first(:conditions=>["SHA(id) = ?",params[:id]])
精彩评论