LoginSignup
13
5

More than 5 years have passed since last update.

ActiveYamlでmodelをyamlファイルで管理する

Posted at

ユースケース

基本的に参照しか行わず、DBで管理する必要がないデータ、定数の集合をyamlしRailsのmodelにインポートして使用する
ex)都道府県、地方など

使い方

1.app/model配下にActiveYamlディレクトリを作成

app/models/ActiveYaml
app
 |- models
    |- ActiveYaml
       |- prefectures.yml
       |- region.yml

2.作成したActiveYamlにymlファイルを作成していく

app/models/ActiveYaml/prefectures.yml
- id: 1
  name: tokyo
  region_id: 1

3.yamlで定義したデータを使用したいモデルに読み込む

app/models/user.rb
class Area < ActiveYaml::Base  
  set_root_path Rails.root.join('app/models/ActiveYaml')
  use_multiple_files
  set_filenames "active_yaml1","active_yaml2"
end

ActiveRecodeも使用できます。

Area.find(1).name
#=> "tokyo"
13
5
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
13
5