This time, I would like to create a select bar for the prefectures that I often see: grin:
gem 'active_hash'
$ bundle install
In my case I add it to the pet model.
rudy:db:migrate
prefecture_id :integer
Create the prefecture.rb file directly in the model and describe the contents.
prefecture.rb
class Prefecture < ActiveHash::Base
self.data = [
{id: 1, name: 'Hokkaido'}, {id: 2, name: 'Aomori Prefecture'}, {id: 3, name: 'Iwate Prefecture'},
{id: 4, name: 'Miyagi Prefecture'}, {id: 5, name: 'Akita'}, {id: 6, name: 'Yamagata Prefecture'},
{id: 7, name: 'Fukushima Prefecture'}, {id: 8, name: 'Ibaraki Prefecture'}, {id: 9, name: 'Tochigi Prefecture'},
{id: 10, name: 'Gunma Prefecture'}, {id: 11, name: 'Saitama'}, {id: 12, name: 'Chiba'},
{id: 13, name: 'Tokyo'}, {id: 14, name: 'Kanagawa Prefecture'}, {id: 15, name: 'Niigata Prefecture'},
{id: 16, name: 'Toyama Prefecture'}, {id: 17, name: 'Ishikawa Prefecture'}, {id: 18, name: 'Fukui prefecture'},
{id: 19, name: 'Yamanashi Prefecture'}, {id: 20, name: 'Nagano Prefecture'}, {id: 21, name: 'Gifu Prefecture'},
{id: 22, name: 'Shizuoka Prefecture'}, {id: 23, name: 'Aichi prefecture'}, {id: 24, name: 'Mie Prefecture'},
{id: 25, name: 'Shiga Prefecture'}, {id: 26, name: 'Kyoto'}, {id: 27, name: 'Osaka'},
{id: 28, name: 'Hyogo prefecture'}, {id: 29, name: 'Nara Prefecture'}, {id: 30, name: 'Wakayama Prefecture'},
{id: 31, name: 'Tottori prefecture'}, {id: 32, name: 'Shimane Prefecture'}, {id: 33, name: 'Okayama Prefecture'},
{id: 34, name: 'Hiroshima Prefecture'}, {id: 35, name: 'Yamaguchi Prefecture'}, {id: 36, name: 'Tokushima Prefecture'},
{id: 37, name: 'Kagawa Prefecture'}, {id: 38, name: 'Ehime Prefecture'}, {id: 39, name: 'Kochi Prefecture'},
{id: 40, name: 'Fukuoka Prefecture'}, {id: 41, name: 'Saga Prefecture'}, {id: 42, name: 'Nagasaki Prefecture'},
{id: 43, name: 'Kumamoto Prefecture'}, {id: 44, name: 'Oita Prefecture'}, {id: 45, name: 'Miyazaki prefecture'},
{id: 46, name: 'Kagoshima prefecture'}, {id: 47, name: 'Okinawa Prefecture'}
]
include ActiveHash::Associations
has_many :pets
end
Added relation to pet model
pet.rb
class Pet < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :prefecture
end
rudy:pets.controller.rb
private
def pet_params
params.require(:pet).permit(:name, :prefecture_id)
end
end
<%= form_with model: @pet, url: pets_path, method: :post, local: true do |f| %>
<%= f.label :"Prefectures" %>
<%= f.collection_select :prefecture_id, Prefecture.all, :id, :name, prompt: "--Please select--" %>
<%= end %>
done! !! : blush:
Recommended Posts