Get the value of enum saved in DB by Rails with attribute_before_type_cast

Introduction

A reminder of how to get the enum value saved in the DB in Rails with attribute_before_type_cast

environment

Reference URL

https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/BeforeTypeCast.html

https://railsdoc.com/page/options_for_select

https://310nae.com/rails-selectbox/

https://qiita.com/ozackiee/items/17b91e26fad58e147f2e

https://ja.stackoverflow.com/questions/72551/enum-でセレクトボックスを表示させてインデックス番号をdb-に保存したい

What is attribute_before_type_cast?

About the value and actual value of the name definition of enum

Please note that when using enum, the value looks different on Rails and the value saved in DB.

Rails enum is implemented so that it can be handled transparently as a character string (or symbol) in the code notation.

As you can see by hitting SQL directly or looking at the record information saved using the DB GUI client, the number is actually saved instead of the string.

Reference URL: <https://ja.stackoverflow.com/questions/72551/enum-%e3%81%a7%e3%82%bb%e3%83%ac%e3%82%af%e3%83%88 % e3% 83% 9c% e3% 83% 83% e3% 82% af% e3% 82% b9% e3% 82% 92% e8% a1% a8% e7% a4% ba% e3% 81% 95% e3 % 81% 9b% e3% 81% a6% e3% 82% a4% e3% 83% b3% e3% 83% 87% e3% 83% 83% e3% 82% af% e3% 82% b9% e7% 95 % aa% e5% 8f% b7% e3% 82% 92db-% e3% 81% ab% e4% bf% 9d% e5% ad% 98% e3% 81% 97% e3% 81% 9f% e3% 81% 84>

The actual value defined by enum behaves as a name definition on Rails.

sample.rb


#blood type(blood_type)Enum definition

  enum blood_type: {
Type A: 0,
B type: 1,
O type: 2,
AB type: 3,
    #Name definition on Rails:Actual value stored in DB
  }

Operation check

Check the operation based on the following assumptions

schema.rb


#Name column in Parson model, blood_Create type column
  create_table "persons", force: :cascade do |t|
    t.string "name"
    t.integer "blood_type"
  end

parson.rb


#blood on model_define type with enum
class Person < ApplicationRecord

  enum blood_type: {
Type A: 0,
B type: 1,
O type: 2,
AB type: 3,
  }
end

attribute_before_type_cast method

Check the operation of attribite_before_type_cast using rails console

$ rails console
> person = Person.create(name: "Alice", blood_type: 0) #Create person object,DB save
:name => "Alice"
:blood_type => "Type A"
> person.blood_type #Get the value on rails
"Type A"
> person.blood_type #Get the class of values ​​on rails
String < Object
> person.blood_type_before_type_cast #Get the value of DB
0
> person.blood_type_before_type_cast #Get the class of DB values
Integer < Numeric

attributes, attributes_before_type_cast method

Use rails console to see the difference in behavior between attributes and attributes_before_type_cast

$ rails console
> person = Person.create(name: "Alice", blood_type: 0) #Create person object,DB save
:name => "Alice"
:blood_type => "Type A"
> person.attributes #Show name definitions on rails
"name" => "Alice"
"blood_type" => "Type A"
> person.attributes_type_before_type_cast #Display the actual value of DB
"name" => "Alice"
"blood_type" => 0

Example of use

In my case I used it to generate a new post form from the value defined in the enum

#HTML you want to output
<select>
  <option value="1">type1</option>
  <option value="2">type2</option>
  <option value="3">type3</option>
</select>

person.rb


# blood_define type with enum
class Person < ApplicationRecord

  enum blood_type: {
Type A: 0,
B type: 1,
O type: 2,
AB type: 3,
  }
end

persons_controller.rb


#Create person object
def new
  @person = Person.new
end

I am using the value obtained by attirbute_before_type_cast to set the default value (selected: value)

Ruby:new.html.erb


#Form generation from enum value
<%= form_with model: @person local: true do |f| %>
  <%= f.select :blood_type, options_for_select(Person.blood_types, @person.expense_before_type_cast), {}  %>
  <%= f.submit %>
<% end %>
#Each value at the time of form generation
<%= form_with model: @Model name do|f| %>
  <%= f.select :Column name, options_for_select(Model name.Column name複数形, @Model name.Column name_before_type_cast), {}  %>
  <%= f.submit %>
<% end %>

** There is a caveat in the empty brackets ({}) in the select tag **

Be sure to set the empty parentheses {}, in the option part even if you do not set the normal option. Without this empty brace, the HTML options would be ignored, so setting id/class doesn't work! It will be that.

Reference URL: https://310nae.com/rails-selectbox/

# options_for_select syntax
options_for_select(Array or hash of elements,Default value, {option}, {htmloption})

Summary

I've never used enums and I was really into it when creating a portfolio, so it was a good study! If you make a mistake, please comment!

Recommended Posts

Get the value of enum saved in DB by Rails with attribute_before_type_cast
[Rails] Get access_token at the time of Twitter authentication with Sorcery and save it in DB
[Enum] Let's improve the readability of data by using rails enum
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
How to get boolean value with jQuery in rails simple form
Replace preview by uploading by clicking the image in file_field of Rails
Get the result of POST in Java
The contents of the data saved by CarrierWave.
[Rails] How to get the user information currently logged in with devise
[Order method] Set the order of data in Rails
How to get the ID of a user authenticated with Firebase in Swift
Implement the Like feature in Ajax with Rails.
Get Enum by reverse lookup from the contents
Specify the default value with @Builder of Lombok
I want to get the value in Ruby
[Java] How to get the key and value stored in Map by iterative processing
Write a test by implementing the story of Mr. Nabeats in the world with ruby
A review of the code used by rails beginners
Get the URL of the HTTP redirect destination in Java
[Swift] Get the number of steps with CMP edometer
Format of the log output by Tomcat itself in Tomcat 8
[Kotlin] Get the argument name of the constructor by reflection
Get the name of the test case in the JUnit test class
[My memo] Let's get along with Pry / DB with Rails
[Java] How to get the maximum value of HashMap
[Ruby / Rails] Set a unique (unique) value in the class
[Java] Get the file in the jar regardless of the environment
[Java] Get the file path in the folder with List
Find the approximate value of log (1 + x) in Swift
SSL in the local environment of Docker / Rails / puma
Roughly the flow of web application development with Rails.
I can't get out of the Rails dbconsole screen
Get the URL of the HTTP redirect destination in Ruby
Branch processing by the return value of RestTemplate and the status code of ResponseEntity in Spring Boot
[Rails] Register by attribute of the same model using Devise
Get the object name of the instance created by the new operator
Get the URL issued by ngrok with the Docker expose plugin
Install by specifying the version of Django in the Docker environment
% rails db: When creating, the LoadError caused by mimemagic is
In Redmine you can get the project with Project.find (<identifier>)
Get only the ID of the container specified by docker ps
[Rails] How to display the list of posts by category
[Swift] Get the timing when the value of textField is changed
[Rails] Where to be careful in the description of validation
Find the number of days in a month with Kotlin
Extract the uniquely identifying value of the table created by PostgreSQL
Get UserAgent in [Rails] controller
Japaneseize using i18n with Rails
Error in rails db: migrate
The story of the first Rails app refactored with a self-made helper
[Rails] How to get the URL of the transition source and redirect
[Java] Get the dates of the past Monday and Sunday in order
Get a proxy instance of the component itself in Spring Boot
[Rails] Suppress unnecessary SQL by utilizing the cache control of the association
[Rails / Heroku / MySQL] How to reset the DB of Rails application on Heroku
[Rails] Talk about paying attention to the return value of where
{The first consecutive 10-digit prime number in the value of e} .com
How to get the id of PRIMAY KEY auto_incremented in MyBatis
Get the public URL of a private Flickr file in Java
Form that receives the value of the repeating item in Spring MVC
I want to change the value of Attribute in Selenium of Ruby