LoginSignup
0
0

More than 1 year has passed since last update.

RailsでActive Hashを使ってカテゴリを作る

Last updated at Posted at 2022-07-11

RailsでActive Hashを使ってカテゴリを作る方法を紹介します。

こちらの記事
https://qiita.com/satoka_com/items/183d22541c3a54e0d878
を参考にしました。

最初にGemfileに、

gem 'active_hash'

を記載して、

$ bundle install

します。

自分の場合だとrecruitmentモデル(求人ページ)にカテゴリを持たせたいと考えているので、
そこにActive Hashを使ってカテゴリを作っていきます。

最初にJobategoryモデルを作成します。

#job_category.rb
class Jobcategory < ActiveHash::Base
  self.data = [
  { id: 1, name: 'サンプル' }, { id: 2, name: 'サンプル2' },  { id: 3, name: 'サンプル3' }
  ]

include ActiveHash::Associations
has_many :recruitments

end

今回の場合だとjobcategoryがrecuirtmentに付くのは一つですが、
recruitmentは複数存在するので、has_manyとなります。
そして、recruitmentモデルにも記載していきます。

#recruitment.rb
class Recruitment < ApplicationRecord
  has_rich_text :content
  has_one_attached :image

  has_many :recruitment_jobtags, dependent: :destroy
  has_many :jobtags, through: :recruitment_jobtags

  validates :image, presence: true
  validates :title, presence: true
  validates :compnay_name, presence: true
  validates :locate, presence: true
  validates :access, presence: true
  validates :work, presence: true
  validates :appeal, presence: true
  validates :want, presence: true
  validates :work_time, presence: true
  validates :money, presence: true
  validates :day_off, presence: true
  validates :reception, presence: true
  validates :other, presence: true
  validates :establishmentdate, presence: true
  validates :employeesnumber, presence: true
  validates :age, presence: true

  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to :job_category
end

こちらは、自テーブルが対象に所属しているため、belongs_toと書きます。
これでmodelの記載は完了です。
次にcreateアクションのviewに記載します。

#new.html.erb
<div id="new">
  <h2>求人投稿</h2>

  <%= form_with(model: @recruitment, local: true ) do |form| %>
    <%= render 'layouts/error_messages', model: form.object %>
    <div class="field">
      <%= form.collection_select(:job_category_id ,  JobCategory.all, :id, :name, { include_blank: '選択してください'}, {class:"job_category"}) %>
    </div>
  <div class="submit">
        <%= form.submit "投稿する" , data: { confirm: 'この内容で投稿しますか?'} %>
      </div>
    </div>
  <% end %>
</div>

こうすると self.dataに入っているデータが表示されて、1つ選択出来るようになります。
そして次にcontrollerの記載をします。

#recruitments_controller.rb
def create
  @recruitment = Recruitment.new(recruitment_params)
  @jobtags = Jobtag.all
  @jobcategories = JobCategory.all

  if @recruitment.save
    redirect_to recruitment_path(@recruitment)
  else
    render "new"
  end
end
  def recruitment_params
    params.require(:recruitment).permit(:title,:image,:compnay_name, :locate,  :access,:work, :work_content, :appeal,:want,:work_time, :money, :day_off, :reception, :other, :employeesnumber,:establishmentdate,:age,:job_category_id , { jobtag_ids: [] })
  end

recruitment_paramsに、job_category_idを追加して、
@jobcategories = JobCategory.all を書きます。
これで無事にjobcategoriesが保存できました。
表示する際は、このように表示します。

<span class="job_category">
	<%= @recruitment.job_category.name %>
</span>

@recruitmentに紐づいているため、このような書き方になります。

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