LoginSignup
0
0

More than 3 years have passed since last update.

ActiveHashについて

Posted at

DB設計をしてる時に便利なgemを見つけたのでまとめてみたいと思います。

ActiveHashとは

都道府県一覧やカテゴリーなど「基本的に変更されないデータ」(区分情報等)があったとします。基本的に変更されないデータであるため、データベースに保存する必要性がありません。

ですがビューファイルなどに都道府県のオプションを書くと見るに耐えないコードになってしまいます。

そういう悩みを解決するのに便利なのがactive_hash。
ハッシュデータをモデルとして定義することで、ActiveRecordと同じように使えることができます。

それでは定義の仕方を見ていきましょう。

まずGemfileにactive_hashを記載して、bundle installします。


gem 'active_hash'

モデル作成

今回はArticleモデルとgenreモデルを作りたいと思います。

rails g model article
rails g model genre --skip-migration

genreモデルには情報をデータベースに持たせないのでマイグレーションファイルを作成する必要はありません。

ハッシュの作成

次にデータをハッシュの形で定義します。

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: '国際' },
   { id: 6, name: 'IT' },
   { id: 7, name: 'エンタメ' },
   { id: 8, name: 'スポーツ' },
   { id: 9, name: 'グルメ' },
   { id: 10, name: 'その他' }
 ]
end

ここで気をつけるのはActiveHash::BaseをGenreモデルに継承することで
ActiveRecordのメソッド(allなど)が使えるようになります。

使用するクラスにアソシエーションを定義する。

ActiveHash::Associations::ActiveRecordExtensionsモジュールをArticleクラスにextendする事で
このモジュールに定義してあるbelongs_to_active_hashメソッドをArticleのクラスメソッドとして
使用する事が出来ています。

app/models/article.rb

class Article < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :genre

  end
end

コンソールで試してみましょう

irb(main):001:0> Article.create(genre_id:1)
=> #<Article id: nil, title: nil, genre_id: 1, created_at: nil, updated_at: nil>

無事Articleモデルでgenreモデルで定義したデータを取得することができました。

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