Active_Hash is a gem that can handle data without saving it in the database by directly describing the unchanged data such as prefecture name and category selection in the model file. By using Active_Hash, you can use ActiveRecord methods for unchanged data described directly in the model file.
Describe the following in the gemfile. Then run bundle install with the command.
gemfile
gem 'active_hash'
This time we will create a Post model and a Category model. Create the Post model as usual.
rails g model post
Use the "--skip-migration" option when creating the Category model. Use "--skip-migration" to prevent the migration file from being generated. This time, we will not create a migration file because we will not save the category information in the database.
rails g model category --skip-migration
Define the Category class in category.rb and inherit from the ActiveHash :: Base class. By inheriting ActiveHash :: Base, you can use ActiveRecord methods for the objects defined in the Category model.
app/models/genre.rb
class Category < ActiveHash::Base
self.data = [
{ id: 1, name: '---' },
{ id: 2, name: 'Toner' },
{ id: 3, name: 'Emulsion' },
{ id: 4, name: 'All-in-one' },
{ id: 5, name: 'cleansing' },
{ id: 6, name: 'Facial wash' },
{ id: 7, name: 'Sunscreen' },
{ id: 8, name: 'lip' },
{ id: 9, name: 'perfume' },
{ id: 10, name: 'Hair color' },
{ id: 11, name: 'Hair styling' },
{ id: 12, name: 'Shampoo and conditioner' },
{ id: 13, name: 'contact lens' }
]
end
The data is stored in an array in the form of a hash.
Create a category_id column in the posts table. It is _id because it gets the category associated with id and saves the id of the category in the posts table. The column type should be ** integer type **.
db/migrate/20XXXXXXXXXXXX_create_articles.rb
~Abbreviation~
t.integer :category_id, null: false
~Abbreviation~
ActiveHash provides a belongs_to_active_hash method. If you want to set up an association for a model created using ActiveHash, use the belongs_to_active_hash method. You can use the belongs_to_active_hash method by writing ActiveHash :: Associations :: ActiveRecordExtensions.
app/models/post.rb
class Post < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :category
end
This time, the data is displayed in pull-down format. Therefore, use the collection_select method to display it.
<%= form.collection_select(Column name to be saved,Array of objects,Items stored in columns(DB column name to be referenced when displaying),Column name displayed in the options,option,html option(class etc.)) %>
ruby:app/views/posts/new.html.erb
<%= f.collection_select(:category_id, Category.all, :id, :name, {}, {class:”category-select"}) %>
https://github.com/zilkey/active_hash
Recommended Posts