在 Rails 应用程序中的 ActiveRecord 模型中使用 Hashids (http://hashids.org/ruby/)。
在 Rails 应用程序中的 ActiveRecord 模型中使用 Hashids (http://hashids.org/ruby/)。
This gem allows you to easily use Hashids in your Rails app. Instead of your models using sequential numbers like 1, 2, 3, they will instead have unique short hashes like "yLA6m0oM", "5bAyD0LO", and "wz3MZ49l". The database will still use integers under the hood, so this gem can be added or removed at any time.
IMPORTANT: If you need to maintain the same hashids from a pre-1.0 release, read the upgrade notes.
Add this line to your application's Gemfile:
gem "hashid-rails", "~> 1.0"And then execute:
$ bundleclass Model
model.hashid
#=> "yLA6m0oM"Additionally, the to_param method is overridden to use hashid instead of id.
This means methods that take advantage of implicit ID will automatically work
with hashids.
Passing a hashid model to `link_to`…
will use `hashid` instead of `id`.
ModelYou can use the Model#find_by_hashid method to find a record without falling
back on the standard find method.
# When a record is found, it returns the record.
@person = Person.find_by_hashid(params[:hashid])
#=>
# When no record, it returns nil
@person = Person.find_by_hashid(params[:hashid])
#=> nil
# A bang (!) version is also available and raises an exception when not found.
@person = Person.find_by_hashid!(params[:hashid])
#=> ActiveRecord::RecordNotFoundYou can add an initializer for Hashid::Rails to customize the options passed to the Hashids gem. This is completely optional. The configuration below shows the default options.
…You can also customize the hashid configuration at the model level.
hashid_config supports all the same options as the Hashid::Rails.configure
block and allows for each model to have a different config. This can be useful
for setting a custom salt/pepper. For instance, the pepper defaults to the table
name, so if you rename the table, you can keep the same hashids by setting the
pepper to the old table name.
class Model NOTE: If it's a significant feature or change, consider creating an Issue for
> discussion before opening a PR.暂无开放 Issues,或尚未同步最近议题。