[RUBY] From introduction to use of ActiveHash

I used to use a gem called ActiveHash while studying Rails, so I'll leave it as a memorandum.

・ What is Active Hash? ・ Introduction of Active Hash ・ How to use ActiveHash (It is long, but you can use it if you follow the procedure)

I would like to touch on these three. I'm still a beginner in programming, so I can't talk deeply.

What is Active Hash?

Active_Hash is a Gem that can handle read-only data without saving it in the database by writing the unchanged data directly in the model file.

To put it simply,

Basically, it is a convenient one that can store data (static data) that does not change, data such as "prefecture" and "city" in hash format in a pseudo model, and call it up.

What's convenient is that you don't have to make a table! !! !! !! If the contents of the data do not change, basically use ActiveHash! It may seem difficult at first, but you will soon get used to it!

Introduction of ActiveHash

First, write the following sentence in the Gemfile

Gemfile


gem 'active_hash'

After writing, let's do bundle install in the terminal!

Terminal


% bundle install

This bundle install command installs the gems written in the Gemfile all at once, so be sure to run it when you add a new Gem!

This completes the Active Hash insertion.

It's easy ♪

How to use ActiveHash

First of all, as a prerequisite, this time we will introduce the procedure of creating a "prefecture" and saving it in the "items" table.

Follow the steps below.

(1) Create a model for storing prefectural data ② Data storage ③ Define the association ④ Describe the foreign key to be acquired in the migration file of items

(1) Create a model for storing prefectural data

Execute the following command in the terminal in the directory you want to create!

Terminal


% rails g model prefecture --skip-migration

Explanation of ①

Create a model of prefecture with rails g model prefecture, then use the option --skip-migration , this option will make the migration file Don't create it, it's an option called . A migration file is a file in the migrate directory in the db directory. This → "db/migrate/2020 ......."

ActiveHash doesn't need this migration file I used -skip-migration .

Terminal


% rails g model prefecture --skip-migration 
Running via Spring preloader in process 26071
      invoke  active_record
      create    app/models/prefecture.rb
      invoke    rspec
      create      spec/models/prefecture_spec.rb
      invoke      factory_bot
      create        spec/factories/prefectures.rb

If these files are generated, you are successful. If you make a mistake and create it with the command "rails g model prefecture" without adding options Execute "rails d model prefecture" to delete the created prefecture model, and then execute "rails g model prefecture --skip-migration" again!

② Data storage

Describe the following in the "app/models/prefecture.rb" file created earlier.

app/models/prefecture.rb


class Prefecture < ActiveHash::Base
  self.data = [
    {id: 1, name: 'Hokkaido'}, {id: 2, name: 'Aomori Prefecture'}, {id: 3, name: 'Iwate Prefecture'},
    {id: 4, name: 'Miyagi Prefecture'}, {id: 5, name: 'Akita'}, {id: 6, name: 'Yamagata Prefecture'},
    {id: 7, name: 'Fukushima Prefecture'}, {id: 8, name: 'Ibaraki Prefecture'}, {id: 9, name: 'Tochigi Prefecture'},
    {id: 10, name: 'Gunma Prefecture'}, {id: 11, name: 'Saitama'}, {id: 12, name: 'Chiba'},
    {id: 13, name: 'Tokyo'}, {id: 14, name: 'Kanagawa Prefecture'}, {id: 15, name: 'Niigata Prefecture'},
    {id: 16, name: 'Toyama Prefecture'}, {id: 17, name: 'Ishikawa Prefecture'}, {id: 18, name: 'Fukui prefecture'},
    {id: 19, name: 'Yamanashi Prefecture'}, {id: 20, name: 'Nagano Prefecture'}, {id: 21, name: 'Gifu Prefecture'},
    {id: 22, name: 'Shizuoka Prefecture'}, {id: 23, name: 'Aichi prefecture'}, {id: 24, name: 'Mie Prefecture'},
    {id: 25, name: 'Shiga Prefecture'}, {id: 26, name: 'Kyoto'}, {id: 27, name: 'Osaka'},
    {id: 28, name: 'Hyogo prefecture'}, {id: 29, name: 'Nara Prefecture'}, {id: 30, name: 'Wakayama Prefecture'},
    {id: 31, name: 'Tottori prefecture'}, {id: 32, name: 'Shimane Prefecture'}, {id: 33, name: 'Okayama Prefecture'},
    {id: 34, name: 'Hiroshima Prefecture'}, {id: 35, name: 'Yamaguchi Prefecture'}, {id: 36, name: 'Tokushima Prefecture'},
    {id: 37, name: 'Kagawa Prefecture'}, {id: 38, name: 'Ehime Prefecture'}, {id: 39, name: 'Kochi Prefecture'},
    {id: 40, name: 'Fukuoka Prefecture'}, {id: 41, name: 'Saga Prefecture'}, {id: 42, name: 'Nagasaki Prefecture'},
    {id: 43, name: 'Kumamoto Prefecture'}, {id: 44, name: 'Oita Prefecture'}, {id: 45, name: 'Miyazaki prefecture'},
    {id: 46, name: 'Kagoshima prefecture'}, {id: 47, name: 'Okinawa Prefecture'}
  ]
end

At this time, there is the following description by default when creating the model, but let's paste it from above, because it is not necessary.

app/models/prefecture.rb


class Prefecture < ApplicationRecord
end

Explanation of ②

・ First of all, "class Prefecture <Application Record" that was originally written Since it says that you should inherit the class called "ApplicationRecord", I deleted it (because I want you to inherit the class called ActiveHash :: Base).

-The basic storage method of ActiveHash is as follows.

How to store active hash



class model class name< ActiveHash::Base
  self.data = [
      {Column name:value, Column name:value}, {Column name:value, Column name:value}
  ]
end

So id and name are column names Integer and Prefecture are values ​​.

③ Define association

This time, I want to take the form of saying, "One product has one prefecture." It becomes "Item belongs to Prefecture". Write the following in item.rb!

models/item.rb


 extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :prefecture

Explanation of ③

・ At this time, the prefecture side "One prefecture has many items" It will be "Prefecture has many Items", but there is no need to describe the association on the prefecture side. When using ActiveHash, it interprets nicely, so you don't have to mention it!

④ Describe the foreign key to be acquired in the migration file of items

Let's add a column to the item migration file to get the foreign key of prefecture! After adding the columns, let's perform the migration! If you are running the migration file, stop it with "rails db: rollback"! Also, if the rails server is running, stop the server with "controll + C" Let's restart the server with "rails s"!

ruby:db/migrate/2020....create_items.rb


class CreateItems < ActiveRecord::Migration[6.0]
  def change
    create_table :items do |t|  
      #↓ Add this one line ↓
      t.integer    :prefecture_id, null: false
      #↑ Add this one line ↑
      foreign_key: true
      t.timestamps
    end
  end
end

Terminal


% rails db:rollback 
↑ Migration file stop command

% rails db:migrate
↑ Migration file execution command

controll +After executing C, execute the following

% rails s
↑ Rails server start command

Explanation of ④

-I'm getting a foreign key, but I'm using the integer type instead of the referenses type, for a reason ,,,

Since we haven't created a prefecture table this time, we can't use the references type!

Investigate the difference between references type and integer type respectively.

-Please note that you must execute the restart command whenever you change the table. I get angry with rails.

⑤ Description method when using

Write the following in the file you want to use This time I want to use it for the items file, so I will describe it in items/index.html.erb.

erb:items/index.html.erb


<%= f.collection_select(:prefecture_id, Prefecture.all, :id, :name, {include_blank: "---"}, {class:"name of the class", id:"id name"}) %>

Explanation of ⑤

Please see below first

<%= form.collection_select(① Column name to be saved,② Array of objects,③ Items saved in the column,④ Column name displayed in the options, ⑤{option}, ⑥{htmloption} ) %>

I will explain one by one - <% = form.collection_select%> is a helper method provided in rails. This represents a pull-down display.

・ The column name saved in ① will be prefecture_id because you want to save the id of prefecture.

-The array of objects in (2) specifies which data to retrieve from the data stored in Prefecture in "(2) Store data". Although the class method called ".all" is used, there are various other methods. Please take a research on it.

・ Let's set the item saved in column ③ to ": id"! ": Name" is fine!

・ ④ Specify ": ​​name" for the column name displayed in the options so that it is easy to understand at a glance.

・ ⑤ {Option} This time, I used {include_blank: "---"} for this option, which means that "---" is displayed if nothing is entered. Point to.

・ ⑥ {html option} This is where you write the HTML class name and id name. This time, I omitted it because it is only for usage. If you need it, please write the class name and id name.

The above is the explanation of how to use ActiveHash!

Summary

ActiveHash is a gem for handling read-only data To install it, write "gem'active_hash'" and then "bundle install". I will do my best to use it

Thank you until the end!

Reference article https://pikawaka.com/rails/active_hash

https://github.com/zilkey/active_hash

Recommended Posts

From introduction to use of ActiveHash
From introduction to usage of byebug
How to use active_hash! !!
How to use enum (introduction of Japanese notation)
[Beginner] How to use devise Change settings from introduction
How to use setDefaultCloseOperation () of JFrame
Introduction to Ruby (from other languages)
[Introduction to Rails] How to use render
Introduction purpose of ActiveHash and simple flow to application implementation
[Java] [Maven3] Summary of how to use Maven3
Output of the book "Introduction to Java"
Introduction to monitoring from Java Touching Prometheus
Introduction to Ruby 2
[Java] Flow from introduction of STS to confirmation of dynamic page on localhost (2/3)
Introduction of milkode
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
[Java] Introduction to Java
Introduction to migration
Introduction to java
Introduction to Doma
[Rails] Introduction of pry-rails ~ How to debug binding.pry
[Docker] Introduction to docker compose Basic summary of docker-compose.yml
Summary of moss when updating from JMockit 1.4 to 1.30
From setup to usage of Selenium wrapper Selenide
How to use JQuery in js.erb of Rails6
[Introduction to Java] Basics of java arithmetic (for beginners)
[Swift] Use Swity JSON to easily get information from JSON data of the fortune-telling API
[Java] How to use compareTo method of Date class
Use of Date class
Introduction to JAR files
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Introduction of Docker --Part 1--
How to use rbenv
How to write Scala from the perspective of Java
Migrate from JUnit 4 to JUnit 5
Introduction to programming for college students (updated from time to time)
How to use letter_opener_web
How to use with_option
How to use java.util.logging
Introduction to bit operation
Introduction to Ratpack (6) --Promise
[Rails] Introduction of PAY.JP
How to use map
Introduction to Ratpack (9) --Thymeleaf
The story of migrating from Paperclip to Active Storage
PATH to use docker-slim
Understand the characteristics of Scala in 5 minutes (Introduction to Scala)
Introduction to PlayFramework 2.7 ① Overview
How to use Twitter4J
Introduction to design patterns (introduction)
How to use hidden_field_tag
Procedure to use S3 of LocalStack for Active Storage
[How to use label]
Introduction to Practical Programming
How to use identity
Introduction to javadoc command
How to use hashes
From Java to Ruby !!
How to use CommandLineRunner in Spring Batch of Spring Boot