An active hash that can be treated as data even if it is not in the database

Introduction

A function that allows you to select a prefecture from the pull-down menu, which is often seen in questionnaires. , You can have the function to post using the form_with method. However, it is easier to use the prefecture if it is managed numerically on the table. In order to be able to manage with numerical values, it is necessary to prepare the prefecture name and the number associated with it in advance. ActiveHash is a convenient function in such cases.

What is Active Hash?

Gem that allows you to handle data without saving it in the database by entering data that basically does not change in the model. Mainly used when you want to display as a pull-down menu in the view.

The official documentation is here

Flow of preparation

  1. Description of Gem
  2. Install Gem
  3. Generate a model

1. Description of Gem

OK on the bottom line of the file

Gemfile


gem 'active_hash'

2. Install Gem

% bundle install

3. Generate a model

%rails g model model name--skip-migration

The model name should be such that the pull-down menus are grouped together. ex) Baseball, soccer, tennis ... When creating a pull-down like, the model name will be sport.

By adding the --skip-migration option, the migration file will not be generated. ActiveHash does not store in the database, so it does not require a migration file.

Hereinafter, the sports pull-down menu will be described as an example.

Flow from description to display

  1. Define and inherit the class
  2. Describe the items in the pull-down menu
  3. Describe the association
  4. Describe validation
  5. Display pull-down menu

4. Define and inherit the class

Change the model created in "3. Model generation" to the following description.

app/models/sport.rb


class Sport < ActiveHash::Base
  self.data = []
end

ActiveRecord methods can be used by inheriting ActiveHash :: Base.

5. Describe the items in the pull-down menu

The contents of the pull-down are hashed into the array.

app/models/sport.rb


class Sport < ActiveHash::Base
  self.data = [
    { id: 1, name: '---' },
    { id: 2, name: 'Baseball' },
    { id: 3, name: 'Soccer' },
    { id: 4, name: 'Tennis' }
  ]
end

6. Describe the association

Below is an explanation of the premise that there is already a table to store another post.

app/models/post.rb


class Post < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
    belongs_to_active_hash :sport
end

ʻExtend ActiveHash :: Associations :: ActiveRecordExtensions allows you to use the belongs_to_active_hash method`.

There is no need to describe the association in the sport model.

* Note that the description is different from the normal association </ font>

7. Describe validation

app/models/post.rb


class Post < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
    belongs_to_active_hash :sport

  validates :sport_id, presence: true #Unable to save empty post

  
  validates :sport_id, numericality: { other_than: 1 } 
                        #The pull-down selection is "--Cannot be saved when
end

8. Display pull-down menu

collection_select method


collection_select(Column name to be saved,Array of objects,Items stored in columns,Column name displayed in the options,option,html option)
collection_select(:sport_id, Sport.all, :id, :name, {}, {class:"sport-select"})

Column name to be saved: In which column of the table to save. Array of objects: If you want to display all the hashes of the array, you can use .all. Items saved in column: I want to save the part of ʻapp / models / sport.rb that was set to ʻid: in the column. Column name displayed in the options: Display the part of ʻapp / models / sport.rbthat was set asname:` in the pull-down menu. Optional: as needed html options: class name, etc.

Finally

Anyway, the collection_select method has too many arguments, which can be confusing ...

Recommended Posts

An active hash that can be treated as data even if it is not in the database
Continuation ・ Active hash that can be handled as data even if it is not in the database ~ Display
Processing when an ID that does not exist in the database is entered in the URL
Even if I write the setting of STRICT_QUOTE_ESCAPING in CATALINA_OPTS in tomcat8.5, it is not reflected.
Isn't it reflected even if the content is updated in Rails?
Even though the property file path is specified in the -cp option, it is not recognized as a classpath.
If you get the error The data ca n’t be read because it is missing in docker for mac
[Rails] If CSS is not applied in collection_select, check if class can be specified.
Try to save the data that can be read by JavaFX as PNG
[Rails] Bootstrap's text-light cannot be inherited by the link_to method because the class is not written as an argument in the method.
The problem that the JDK set in JAVA_HOME does not appear even if java -version is performed at the command prompt
Is there an instance even if the constructor fails?
[Quarkus] A trap that doesn't work even if you copy and paste the GCP Pub / Sub sample as it is
Directory is not created even if directory task is described in Rakefile
It doesn't work if the Map key is an array
The case that @Autowired could not be used in JUnit5
[Firebase] The problem that the currentUser of Firebase Auth does not become null even if the app is uninstalled.
Solved the phenomenon that "Response time is too long" in the original domain even though the IP address and EC2 address can be entered in the site.
[Rails] What to do if data is not registered in DB
Like function The part that is stuck in making it asynchronous
It seems that data class-like functions will be added in Java14
It should be the same as the sample when logging in to Twitter, but an error occurs ~ resolution
Pay.JP Solution when it can be done locally but it does not work well in the production environment
Are you still exhausted to implement the search function? Gem'ransack' that can be implemented in an instant
I separated the same description as a method under private in Rails controller and implemented it so that it can be called by before_action
Data is not registered in Rails.
What to do if the prefix c is not bound in JSP
About the problem that the server can not be started with rails s
Memo: [Java] If a file is in the monitored directory, process it.
[Rails] About the error that the image is not displayed in the production environment
Get the type of an array element to determine if it is an array
The story that the Servlet could not be loaded in the Java Web application
Phenomenon that cannot log out even though it is described in devise
[Android Studio] Description that can be continuously input in SQLite Database [Java]
A story that suffered from a space that does not disappear even if trimmed with Java The cause is BOM
If the JDK version is correct in Eclipse but an error occurs or the compiler does not work properly