0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】ActiveHash(Gem)について

Last updated at Posted at 2025-06-13

記事概要

Ruby on RailsのActiveHash(Gem)について、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している
  • ActiveHashを用いて実装する「クラス」を、便宜上「モデル」と呼称する

サンプルアプリ(GitHub)

ActiveHashとは

変更されないデータをモデルファイル内に直接記述することで、データベースへ保存せずにデータを取り扱うことができるGem

ActiveHash::Base

あるモデル内(クラス内)でActiveHashを用いる際に必要となるクラス
ActiveHashのGemに定義されており、ActiveHash::Baseを継承することで、ActiveRecordと同じようなメソッドを使用できる

Gemのインストール手順

Gemfileの記述

手順①(モデルの作成)

  1. ActiveHashを利用するモデルを作成済みの場合は、手順②へ進む
  2. モデルを作成する
    % rails g model [モデル名]
    
  3. マイグレーションファイルを編集する
    db/migrate/20XXXXXXXXXXXX_create_articles.rb
    class CreateArticles < ActiveRecord::Migration[7.0]
     def change
       create_table :articles do |t|
         t.string     :title        , null: false
         t.text       :text
         
         # カラム名は、[ActiveHashのモデル名]_id
         # カラム型は、integer
         t.integer    :genre_id     , null: false
         t.timestamps
       end
     end
    end
    
    ※ActiveHashを紐づけるテーブルの中で、ActiveHashのモデルのidを外部キーとして管理することで、テーブルデータに紐付いたジャンルの取得が実現できる
  4. マイグレーションを実行し、テーブルを作成する

手順②(ActiveHashのモデル作成)

  1. app/models配下に、ActiveHashのモデルを手動作成する
    app/models/[ActiveHashのモデル名].rb
  2. 作成したActiveHashのモデルにActiveHash::Baseを継承する
    [ActiveHashのモデル名].rb
    class モデル名 < ActiveHash::Base
    end
    
  3. データは、配列にハッシュ形式で格納する
    app/models/genre.rb
    class Genre < ActiveHash::Base
     self.data = [
       { id: 1, name: '経済' },
       { id: 2, name: '政治' },
       { id: 3, name: '地域' },
       { id: 4, name: '国際' },
       { id: 5, name: 'IT' },
       { id: 6, name: 'エンタメ' },
       { id: 7, name: 'スポーツ' },
       { id: 8, name: 'グルメ' },
       { id: 9, name: 'その他' }
     ]
    end
    

手順③(アソシエーションを設定)

  1. ActiveHashを利用するモデルに、アソシエーションを設定する
    1. extend ActiveHash::Associations::ActiveRecordExtensionsと記述して、moduleを取り込む
    2. belongs_toを設定する
    app/models/article.rb
    class Article < ApplicationRecord
      extend ActiveHash::Associations::ActiveRecordExtensions
      belongs_to :genre
    end
    
  2. ActiveHashのモデルに、アソシエーションを設定する
    • 保存データを使用(ビューなど)しない場合は、アソシエーションの定義は不要
    • 保存データを使用(ビューなど)する場合は、必ずアソシエーションを定義
      1. include ActiveHash::Associationsと記述して、moduleを取り込む
      2. has_manyを設定する
      app/models/genre.rb
      class Genre < ActiveHash::Base
       self.data = [
         { id: 1, name: '経済' },
         { id: 2, name: '政治' },
         { id: 3, name: '地域' },
         { id: 4, name: '国際' },
         { id: 5, name: 'IT' },
         { id: 6, name: 'エンタメ' },
         { id: 7, name: 'スポーツ' },
         { id: 8, name: 'グルメ' },
         { id: 9, name: 'その他' }
       ]
      
        include ActiveHash::Associations
        has_many :articles
       end
      

手順④(バリデーションを設定)

ActiveHashを利用するモデルに対して、バリデーションを設定する

  1. 全項目NULLで保存できないように、最低1項目はNULL制約をつける
    app/models/article.rb
    class Article < ApplicationRecord
      extend ActiveHash::Associations::ActiveRecordExtensions
      belongs_to :genre
    
      #空の投稿を保存できないようにする
      validates :title, presence: true
    end
    
  2. ActiveHashを紐づけている項目は、数値の場合のみデータを保存する
    app/models/article.rb
    class Article < ApplicationRecord
      extend ActiveHash::Associations::ActiveRecordExtensions
      belongs_to :genre
    
      #空の投稿を保存できないようにする
      validates :title, presence: true
    
      #数値以外を保存できないようにする
      validates :genre_id, numericality: true
    end
    

手順⑤(ビューでの表示)

  1. データを表示する
    アソシエーションが定義されている場合、単一レコード情報.ActiveHashを用いたモデル名.カラム名で情報を取得できる
    <!-- コントローラーで、「@articles = Article.all」を定義 -->
    
    <% @articles.each do |article| %>
      <!-- ActiveHashで紐付けた情報を表示する -->
      <%= article.genre.name %>
    <% end %>
    
  2. collection_selectメソッドを使用して、form_withへ追加する
    <%= form_with model: @article, url:articles_path, local: true do |f| %>
      <%= f.text_field :title, class:"title", placeholder:"タイトル" %>
      <%= f.text_area :text, class:"text", placeholder:"テキスト" %>
    
      <!-- ActiveHashのモデルデータを表示 -->
      <%= f.collection_select(:genre_id, Genre.all, :id, :name, {}, {class:"genre-select"}) %>
      <%= f.submit "投稿する" ,class:"btn" %>
    <% end %>
    

Ruby on Railsまとめ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?