LoginSignup
0
1

More than 3 years have passed since last update.

ActiveHashを使ってカテゴリーの選択を実装

Last updated at Posted at 2020-11-27

ActiveHashとは「基本的に変更されないデータの取り扱い」があったとします。このデータはデータベースに保存する必要がありません。一方、ビューファイルなどにそれらのデータを直接書いてしまうと、可読性に欠けます。そのようなケースでは、ActiveHashが有用です。

ActiveHashをインストール

Gemfile
 gem 'active_hash'
ターミナル
bundle install

モデル生成(今回はカテゴリー選択を"genre"とします)

ターミナル
rails g model genre --skip-migration

この時のモデル作成には「--skip-migration」を使用しております。
これはモデルファイルを作成するときに、マイグレーションファイルの生成を行わないためのオプションです。
選択したジャンルの情報はデータベースに保存しないため、マイグレーションファイルを作成する必要がないためです。

ActiveHash::Base

ActiveHash::Baseは、あるモデル内(クラス内)でActiveHashを用いる際に必要となるクラスです。

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: 'その他' }
 ]
   include ActiveHash::Associations
   has_many :articles

 end

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

class CreateArticles < ActiveRecord::Migration[6.0]
 def change
   create_table :articles do |t|
     t.string     :title        , null: false
     t.text       :text         , null: false
     t.integer    :genre_id     , null: false
     t.timestamps
   end
 end
end
ターミナル
% rails db:migrate

親モデルのアソシエーションを設定
belongs_toの記述を行います。

app/models/article.rb
class Article < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to :genre
  validates :title, :text. presence: true
  validates :genre_id, numericality: { other_than: 1 } 
end
app/views/articles/new.html.erb
<%= form_with model: @article, url:articles_path, local: true do |f| %>
  <div class="article-box">
    記事を投稿する
    <%= f.text_field :title, class:"title", placeholder:"タイトル" %>
    <%= f.text_area :text, class:"text", placeholder:"テキスト" %>
    <%= f.collection_select(:genre_id, Genre.all, :id, :name, {}, {class:"genre-select"}) %>
    <%= f.submit "投稿する" ,class:"btn" %>
  </div>
<% end %>

以上備忘録でした。

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