How to use Enum in Ruby and Rails A memo to remember.
"Enum" means "enumeration type". -DB is registered as int type or boolean type, and any key name associated with the numerical value can be given. -In the source code, the associated key name is used.
advantage -If the data type is set to integer, it will be registered as a number in the DB, but if it is only a number, the meaning of the number cannot be shared. -If you define it as a character string, there is a high possibility of typing, but if you use an enum, you do not have to worry about it. ・ Easy to correct.
You need to define an enum for your model. There are two definition methods. ** 1. Definition only ** ** 2. Specify a numerical value in the definition **
Define with an array. They are linked in order from 0 in the order of definition. In the example below, yesterday → 0, today → 1, tomorrow → 2 are automatically sorted. enum column name: Specify enum with [: key name you want to give].
** * [] Nanoto: Pay attention to the position **
Model file
enum column name: [ :yesterday, :today, :tomorrow]
↑ What to define
enum Column name: {Key name you want to add: Corresponding number} Specify enum. ** * {} and: Pay attention to the position **
Model file
enum column name: {yesterday: 0,today: 1,tomorrow: 2 }
↑ What to define
You can create a select box with the description below. ** Column name and multiple column types are the same column and the column described after enum ** ** The model name is the model described at the time of definition **
view file
<%= select :Column name, :name,Model name.Column name複数形.keys.to_a, include_blank: true %>
・ I used it when changing the status or when the status was changed in conjunction with it. ・ When comparing with if etc. on the controller, I think that you can compare with defined characters instead of numbers. Example) if Information you want to compare == "Yesterday" Example) Information you want to find .where (column name: "today") .count etc.
Recommended Posts