LoginSignup
0
2

More than 3 years have passed since last update.

ActiveHashの導入の手順について

Posted at

概要

Webページで都道府県や商品のカテゴリーなどで使用されるActiveHash。その導入の手順についてここに記述します。

※マイグレーションファイルやHTMLはすでに作ってある前提です。

手順

1.GemfileにActiveHashを記述

2.モデルを作成する

3.ActiveHash::Baseに変更

4.アソシエーションを設定

1.GemfileにActiveHashを記述

Gemfileに「gem 'active_hash'」を記述。

Gemfile.
gem 'active_hash'

新しいGemを入れたのでターミナルで「bundle install」をする。

ターミナル.
bundle install

2.モデルを作成する

ターミナル.
rails g model モデル名(例として都道府県のモデルarea.rbを作ります)

3.ActiveHash::Baseに変更

area.rb
class Photo < ActiveHash::Base

end

4.アソシエーションを設定

関連しているモデルにアソシエーションを記述(例としてitem.rbとします。)

item.rb
class Item < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :area
end

belongs_to_active_hashを定義するためにextend ActiveHash::Associations::ActiveRecordExtensionsを記述。

area.rb
class Area < ActiveHash::Base
    self.data = [

      {id: 1, name: '--'},
      {id: 2, name: '北海道'}, 
      {id: 3, name: '青森県'}, 
      {id: 4, name: '岩手県'},
      {id: 5, name: '宮城県'}, 
  #中略

    ]
    include ActiveHash::Associations
    has_many :photos
end

area.rbにもアソシエーションを記述。以上でActiveHashを導入することができる

0
2
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
2