[RUBY] Rails enum Select prefecture by pull-down method

Introduction

I made it possible to acquire map information by linking with Google API with a personal development application.

Since it is troublesome to manually enter all the addresses, I will try to make it possible to select the prefecture by pull-down method.

ruby:new.html.erb



<%= form_for @ride, method: :post do |f| %>
 <%= f.select :prefecture, ['Hokkaido', 'Aomori Prefecture', 'Akita', 'Iwate Prefecture'The following is omitted], { include_blank: 'Please select' } %>
<% end %>

If you ignore the readability of the code and implement it, you just enter it like this,

When I entered all 47 prefectures on the view side like this, I thought it was ** very unsightly **, so I searched for a smart way to do it.

enum There seems to be an enum, which allows you to write it in a model instead of a view,

You can make the code on the view side quite refreshing!

python


class CreateRides < ActiveRecord::Migration[5.2]
  def change
    create_table :Rides do |t|
      t.integer :ride_area, null: false, default: 0
    end
end

First, create a column with integer.

ride.rb


class Ride < ApplicationRecord
 enum ride_area:{
     "---":0,
Hokkaido:1,Aomori Prefecture:2,Iwate Prefecture:3,Miyagi Prefecture:4,Akita:5,Yamagata Prefecture:6,Fukushima Prefecture:7,
Ibaraki Prefecture:8,Tochigi Prefecture:9,Gunma Prefecture:10,Saitama:11,Chiba:12,Tokyo:13,Kanagawa Prefecture:14,
Niigata Prefecture:15,Toyama Prefecture:16,Ishikawa Prefecture:17,Fukui prefecture:18,Yamanashi Prefecture:19,Nagano Prefecture:20,
Gifu Prefecture:21,Shizuoka Prefecture:22,Aichi prefecture:23,Mie Prefecture:24,
Shiga Prefecture:25,Kyoto:26,Osaka:27,Hyogo prefecture:28,Nara Prefecture:29,Wakayama Prefecture:30,
Tottori prefecture:31,Shimane Prefecture:32,Okayama Prefecture:33,Hiroshima Prefecture:34,Yamaguchi Prefecture:35,
Tokushima Prefecture:36,Kagawa Prefecture:37,Ehime Prefecture:38,Kochi Prefecture:39,
Fukuoka Prefecture:40,Saga Prefecture:41,Nagasaki Prefecture:42,Kumamoto Prefecture:43,Oita Prefecture:44,Miyazaki prefecture:45,Kagoshima prefecture:46,
Okinawa Prefecture:47
   }
end

On the model side, write the prefecture like this.

The hash key is displayed in the select box.

ruby:new.html.erb



<%= form_for @ride, method: :post do |f| %>
 <%= f.select :prefecture, Ride.ride_areas.keys, {} %>
<% end %>

Let's rewrite the code written at the beginning like this.

By writing Ride.ride_areas.keys, {}, all the prefectures written in the model will be processed in order, so you can select the prefecture by pull-down method on the browser!

that's all.

Recommended Posts

Rails enum Select prefecture by pull-down method
rails method
[Java] Dynamic method call by reflection of enum (enum)
Rails delegate method
[Rails 6] Validation by belongs_to
[Rails] devise helper method
[Rails] devise introduction method
[Enum] Let's improve the readability of data by using rails enum