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'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!
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.
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
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!
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 .
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!
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 ,,,
-Please note that you must execute the restart command whenever you change the table. I get angry with rails.
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!
Thank you until the end!
Reference article https://pikawaka.com/rails/active_hash
https://github.com/zilkey/active_hash
Recommended Posts