“ActiveHash“使ったことあるでしょうか?
今回は、RailsアプリケーションでActiveHashを使用する方法を解説していきます。
目次
ActiveHashのミニアプリ作成 ~準備~
それでは、アプリを作成していきましょう。
開発環境は、以下のようになります。
- ruby 2.6.5
- rails 6.0.0
今回は、旅行した思い出を投稿できるミニアプリを作成していきます。
# アプリケーションの作成
rails _6.0.0_ new active_hash_app -d mysql
# active_hash_appのディレクトリに移動
cd active_hash_app
# テーブルの作成
rails db:create
テーブルの作成ができたら、”ActiveHash“を導入していきます。
Gemfileに以下の記述をしましょう。
gem 'active_hash'
記述することができたら、ターミナルで
bundle install
を実行してください。
これから、実装に移っていきたいと思います。
ActiveHashのミニアプリ作成 ~実装~
実装に取り掛かっていきます。
まずは、コントローラーとビューファイルを作成していきます。
ターミナルで以下のコマンドを実行しましょう。
rails g controller memories index new
コントローラーが作成できたら、ルーティングを設定しましょう。
config/routes.rbを以下のように記述してください。
Rails.application.routes.draw do
root "memories#index"
resources :memories, only: [:index, :new, :create]
end
記述することができたら、app/models直下に各モデルを作成していきます。
ディレクトリの構造は以下のようになります。
- models
- memory.rb
- prefecture.rb
各モデルをコマンドで作成していきます。
# memory.rbの作成
rails g model memory
# prefecture.rbの作成、マイグレーションファイルが作成されないようにする
rails g model prefecture --skip-migration
作成することができたら、prefecture.rbを以下のように記述しましょう。
class Prefecture < ActiveHash::Base
self.data = [
{ id: 1, name: '---' }, { id: 2, name: '北海道' }, { id: 3, name: '青森県' },
{ id: 4, name: '岩手県' }, { id: 5, name: '宮城県' }, { id: 6, name: '秋田県' },
{ id: 7, name: '山形県' }, { id: 8, name: '福島県' }, { id: 9, name: '茨城県' },
{ id: 10, name: '栃木県' }, { id: 11, name: '群馬県' }, { id: 12, name: '埼玉県' },
{ id: 13, name: '千葉県' }, { id: 14, name: '東京都' }, { id: 15, name: '神奈川県' },
{ id: 16, name: '新潟県' }, { id: 17, name: '富山県' }, { id: 18, name: '石川県' },
{ id: 19, name: '福井県' }, { id: 20, name: '山梨県' }, { id: 21, name: '長野県' },
{ id: 22, name: '岐阜県' }, { id: 23, name: '静岡県' }, { id: 24, name: '愛知県' },
{ id: 25, name: '三重県' }, { id: 26, name: '滋賀県' }, { id: 27, name: '京都府' },
{ id: 28, name: '大阪府' }, { id: 29, name: '兵庫県' }, { id: 30, name: '奈良県' },
{ id: 31, name: '和歌山県' }, { id: 32, name: '鳥取県' }, { id: 33, name: '島根県' },
{ id: 34, name: '岡山県' }, { id: 35, name: '広島県' }, { id: 36, name: '山口県' },
{ id: 37, name: '徳島県' }, { id: 38, name: '香川県' }, { id: 39, name: '愛媛県' },
{ id: 40, name: '高知県' }, { id: 41, name: '福岡県' }, { id: 42, name: '佐賀県' },
{ id: 43, name: '長崎県' }, { id: 44, name: '熊本県' }, { id: 45, name: '大分県' },
{ id: 46, name: '宮崎県' }, { id: 47, name: '鹿児島県' }, { id: 48, name: '沖縄県' }
]
include ActiveHash::Associations
has_many :memories
end
ActiveHash::Baseは、ActiveHashを用いるときに必要となるクラスです。
Gemに定義されています。
ActiveHash::Baseを継承することで、ActiveRecordと同じようなメソッドを使用することができるようになります。
memory.rbを以下のように記述しましょう。
class Memory < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :prefecture
#空の投稿を保存できないようにする
validates :title, :text, presence: true
#ジャンルの選択が「--」の時は保存できないようにする
validates :prefecture_id, numericality: { other_than: 1 }
end
ActiveHashとのアソシエーションを記述する場合は、
extend ActiveHash::Associations::ActiveRecordExtensions
を記述して、moduleを取り込みます。
次にmemoryのマイグレーションファイルを以下のように記述しましょう。
class CreateMemories < ActiveRecord::Migration[6.0]
def change
create_table :memories do |t|
t.string :title, null: false
t.integer :prefecture_id, null: false
t.text :text, null: false
t.timestamps
end
end
end
記述することができたら、以下のコマンドを実行しテーブルを作成しましょう。
rails db:migrate
テーブルを作成することができたら、コントローラーとビューを作成していきましょう。
まずは、コントローラーです。以下のように記述しましょう。
記述に関しては詳しく解説しません。わからない部分は調べてみましょう。
memories_controller.rb
class MemoriesController < ApplicationController
def index
@memories = Memory.all
end
def new
@memory = Memory.new
end
def create
@memory = Memory.new(memory_params)
if @memory.save
redirect_to root_path
else
render :new
end
end
private
def memory_params
params.require(:memory).permit(:title, :text, :prefecture_id)
end
end
次にビューを作成していきます。
memories/index.html.erbを以下のように記述しましょう。
<h1>旅の思い出一覧</h1>
<%= link_to "投稿する", new_memory_path %>
<% @memories.each do |memory| %>
<div class="memory">
<div class="memory-box">
タイトル:<%= memory.title %>
</div>
<div class="memory-box">
旅行した都道府県:<%= memory.prefecture.name%>
</div>
<div class="memory-box">
旅行の内容や感想:<%= memory.text %>
</div>
</div>
<% end %>
memories/new.html.erbを以下のように記述しましょう。
<%= form_with model: @memory, local: true do |f| %>
<div class="prefecture-box">
旅の思い出を投稿する
<%= f.text_field :title, class:"title", placeholder:"タイトル" %>
<%= f.text_area :text, class:"text", placeholder:"旅の内容や感想" %>
<%= f.collection_select(:prefecture_id, Prefecture.all, :id, :name, {}, {class:"prefecture-select"}) %>
<%= f.submit "投稿する", class: "btn" %>
</div>
<% end %>
テーブルをプルダウン形式で表示させることができるメソッドになります。
<%= f.collection_select(:prefecture_id, Prefecture.all, :id, :name, {}, {class:"prefecture-select"}) %>
<%= f.collection_select(:保存したいカラム名, オブジェクトの配列, :保存される項目, 表示したい項目, オプション, htmlオプション) %>
ActiveHashの情報をプルダウンで表示するためには、上記の記述が必要となります。
第一引数から第四引数までは、必ず指定 しましょう。
cssに関しては、参考程度に記載しておきます。
index.css
.memory{
display: flex;
align-items: left;
flex-direction: column;
border: 1px solid #fff;
padding: 20px;
}
.memory-box{
width: 500px;
font-size: 16px;
padding: 5px;
background-color: lightblue;
text-align: left;
}
new.css
.prefecture-box {
height:800px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.title {
height: 30px;
width: 300px;
margin: 20px;
}
.text {
height: 100px;
width: 300px;
resize:none;
margin-bottom: 20px;
}
.prefecture-select{
height: 30px;
width: 250px;
}
.btn {
width: 200px;
margin-top: 20px;
padding: 15px;
border: 1px solid white;
background-color: yellowgreen;
color: white;
}
ここまで記述することができたら、実際にサーバーを起動して投稿することができるか確認してみましょう。
上記は、投稿画面になります。
↑プルダウンの表示
投稿が一覧表示で見ることができました。
画像と同じように表示することができましたでしょうか。
これで実装は終了になります。
ActiveHashの導入はそこまで難しくないかと思います。
ぜひ活用していきましょう。
最後までご覧頂きありがとうございました。