0
1

More than 3 years have passed since last update.

【Rails】gem ' active_hash' プルダウンメニュー作成

Last updated at Posted at 2020-05-16

手順

1:gem導入
2:手動でモデルを作成
3:データを引っ張る
4:アソシエーションを定義
5:実装中のエラー

1:gem 導入

Gemfail.
gem 'active_hash'

bundle installする。

2:モデル作成

※モデルは手動で作成

model/shipping_fee.rb
class ShippingFee < ActiveHash::Base
  self.data = [
      {id: 1, name: '送料込み(出品者負担)'}, {id: 2, name: '着払い(購入者負担)'}
  ]
end

ターミナルで確認:

[2] pry(main)> ShippingFee.find(1)
=> #<ShippingFee:0x00007fa012181140 @attributes={:id=>1, :name=>"送料込み(出品者負担)"}>

3:プルダウンメニューにデーターを引っ張る

new.html.haml
.new-contents__box__title
  発送量の負担
  %supan{class: "required"} 必須
= f.collection_select :shipping_fee_id, ShippingFee.all, :id, :name, {prompt: "選択してください"}, {class: ""}

ShippingFee.allでモデルからデータを取得。
保存されるテーブルのカラムには、idが保存される。

sihpping_fee_id
1
15
4
24

4:アソシエーションを定義

item.rb
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :shipping_fee

active_hashにはbelongs_to_active_hashメソッドが用意されているため、
親になるモデルのみにアソシエーションを定義する。

アソシエーションの確認:

[5] pry(main)> item = Item.find(1)
[6] pry(main)> item.shipping_fee
=> #<ShippingFee:0x00007fa012181140 @attributes={:id=>1, :name=>"送料込み(出品者負担)"}>

5:実装中のエラー

LoadError Unable to autoload constant ShippingFee
原因:作成したモデルのクラス名

model/shipping_fee.rb
#修正前
class Shipping_fee < ActiveHash::Base

#修正後
class ShippingFee < ActiveHash::Base
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