LoginSignup
0
0

More than 1 year has passed since last update.

【Rails API】hash値で検索をかけたい場合

Posted at

はじめに

調整さんのようなWebアプリを作成していて、ルーティング・コントローラー内で、イベントをidではなくhash化されたidを使用した時の備忘録

マイグレーションファイル

class CreateEvents < ActiveRecord::Migration[7.0]
  def change
    create_table :events do |t|
      t.references :user, foreign_key: true, null: false
      t.references :category, foreign_key: true, null: true
      t.string :name, null: false
      t.text :description, null: false
      t.boolean :is_public, null: false, default: true
      t.string :hashed_url, null: false
      t.datetime :deleted_at, null: true

      t.timestamps

      t.index :name
      t.index :hashed_url, unique: true
    end
  end
end

eventテーブルにhashed_urlカラムを作成した。
こちらに保存されたhash値を使い、調整さんのようにhash化されたURLでイベントを管理できるようにしていく
http://hogehoge/api/events/c38d9f25-18ce-4133-8ce9-8d7e3abca9
↑URLイメージ

実装

event作成時にhashed_urlを自動生成

events_controller.rb
class Api::EventsController < ApplicationController

  def create
    event = Event.new(event_params.merge(hashed_url: SecureRandom.uuid))
    if event.save
      render json: event
    else
      render json: event.errors, status: :unprocessable_entity
    end
  end

  private

  def event_params
    params.require(:event).permit(
      :name,
      :category_id,
      :user_id,
      :is_public,
      :description
    )
  end

SecureRandom.uuidで生成されたhash値をmergeメソッドで受け取り、eventテーブルに保存

hashed_urlでイベントの詳細表示

routes.rb
Rails.application.routes.draw do
  namespace :api do
    resources :events, param: :hashed_url
  end
end

routes.rbでhashed_urlをparamとして受け取り設定

events_controller.rb
class Api::EventsController < ApplicationController
  before_action :set_show_event, only: %i(show)

  def show
    render json: @event
  end

  private
  
  def set_show_event
    @event = Event.find_by(hashed_url: params[:hashed_url])
  end

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