[RUBY] How to create multiple pull-down menus with ActiveHash

【Overview】

1. Conclusion </ b>

2. What is ActiveHash </ b>

3. How to use </ b>

4. Supplement </ b>

  1. Conclusion

Create multiple models and list them all in db / migrate!


2. What is Active Hash

ActiveHash is a gem that can handle data by writing unchanged data to a model file without saving it in the DB one by one </ b>!


3. How to use

The introduction method of ActiveHash is the same as other gems, so I will omit it! Also, prepare a table that you want to reflect.

console


%rails g model abcdefghi --skip-migration

I will describe it! The reason for skipping is that there is no need to migrate to the DB (create a table)!

Then

model


 class Abcdefghi <ApplicationRecord

Because it is Let's rewrite ApplicationRecord to ActiveHash :: Base </ b>! You can also use ApplicationRecord methods by inheriting to ActiveHash :: Base! (ActiveHash :: Base can use similar methods of ApplicationRecord)

model


 class Abcdefghi <ActiveHash::Base
self.data = [
   { id: 1, name: '--' },
   { id: 2, name: 'A' },
   { id: 3, name: 'B' },
   { id: 4, name: 'C' },
   { id: 5, name: 'D' },
   { id: 6, name: 'E' },
   { id: 7, name: 'F' },
   { id: 8, name: 'G' },
   { id: 9, name: 'H' },
   { id: 10, name: 'I' }
 ]

As if creating a table with self.data, use the hash in the array format. The contents that are pulled from the database to the model are exactly like this.

"{Id: 1, name:'-'}" is something you often see when displaying.

Repeat this from the beginning of 3. as many times as you want to create a pull-down menu!

db/migrate/20******


 class Create****(Corresponding table name) <ActiveRecord::Migration[6.0]
 def change
   create_table :*****(Corresponding table name)  do |t|
     t.integer    :abcdeghi_id     , null: false
     t.timestamps
    end
  end
 end

will do!

The reason for using _id is to bring the id of the model to the table you want to save.

The rest is as usual

console


% rails db:migrate

All you have to do is OK!

However, what I want to be careful about here is It is an association. For the time being, class Abcdefghi <ActiveHash :: Base has a structure like a DB table, so it is necessary to describe the association.

models/****.rb


class (Corresponding table name)  < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :abcdeghi
end

Please!


4. Supplement

model/****.rb


class ****(Corresponding table name)< ApplicationRecord
validates :abcdefghi_id, numericality: { other_than: 1 }

By writing "{id: 1, name:'--'}" You can write validation that except "-" can be saved </ b>! It means that numbers above id: 1 will be reflected!


Recommended Posts