LoginSignup
0
0

More than 1 year has passed since last update.

リンクの/book/1/とかをハッシュ化するgemのhashids.rbがめちゃ簡単に搭載できた~!

Posted at

Railsでbook#showとかのメゾットだと/book/1とか/book/2とかIDがバレてしまうので、これを使うと/book/Gdwksoとか/book/kDmesrとかに勝手にしてくれる

公式読んでやってみたら15分くらいで出来てめちゃくちゃ簡単だったのでメモー!
色々変更になるかもしれないのでちゃんとしたものは公式をご参照くださいっ
https://github.com/jcypret/hashid-rails

①インストール

Gemfile
gem "hashid-rails", "~> 1.0"
console
$ bundle install

②設定を行う

config/initializerにhashid.rbを作成して下記を追加

config/initializer/hashid.rb
Hashid::Rails.configure do |config|
  # The salt to use for generating hashid. Prepended with pepper (table name).
  config.salt = "yasashii oshio" #ここは任意に言葉を変えます

  # The minimum length of generated hashids
  config.min_hash_length = 6

  # Whether to override the `find` method
  config.override_find = true

  # Whether to override the `to_param` method
  config.override_to_param = true

  # Whether to sign hashids to prevent conflicts with regular IDs (see https://github.com/jcypret/hashid-rails/issues/30)
  config.sign_hashids = true
end

"yasashii oshio"のところはENV['HASHIDS_SALT']みたいに環境変数化しても大丈夫です

model
class Book < ApplicationRecord
  include Hashid::Rails #この一行を追加
:
:
end

hashidsを使いたいモデルに上記を追加します

これで終わり!
Book.find(params[:id])がオーバーライドされて勝手にハッシュのIDで何とかしてくれます(すごい)

find_byを使いたいとき

controller
book = Book.find_by_hashid(params[:id])

これでBook.find_by(id: params[:id])のような使い方が出来、該当がない時はnilで帰ってきます。
他の使い方は分からないです・・・m(_ _)m


相違点あったら教えてくださると嬉しいです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0