--- Title: '【Rails5】Deviseを使って会員登録を行い、郵便番号から住所を自動入力にする方法 #rails #郵便番号' Keywords: - rails - 郵便番号 Author: michiru Web: https://mimemo.io/m/5dn7jlK2BXor9Ye --- ![s_2019-11-04 (2)](https://mimemo.s3-ap-northeast-1.amazonaws.com/attachment/8ec4eb51-8137-493f-ba71-73808a7f7c6d.png) ### 1. rails new myappをターミナルで実行 ``` $ rails new myapp #myappのところには自由に名前を入れる ``` ### 2. gemに下記を追加し bundle install ```:Gemfile=7 gem 'sqlite3', '~> 1.3.13' #sqlite3には ~> 1.3.13を足す gem 'devise' gem 'jp_prefecture' gem 'jquery-rails' #rails5はこれを入れないとjQueryが動かない ``` ``` $ bundle install ``` ### 3. Deviseを導入(ターミナルで実行) ``` $ rails g devise:install $ rails g devise User $ rails g devise:controllers users $ rails g devise:views ``` ### 4. routes.rb(ルーティング設定) ```:routes.rb=1 Rails.application.routes.draw do devise_for :users, :controllers => { :registrations => 'users/registrations', :sessions => 'users/sessions' } end ``` 5. ホーム画面を作っておく。 ``` $ rails g controller welcome index ``` ```:routes.rb=1 Rails.application.routes.draw do root 'welocome#index' #追加 devise_for :users, :controllers => { :registrations => 'users/registrations', :sessions => 'users/sessions' } end ``` ### 5. userテーブルに郵便番号用下記カラム追加 (ターミナルで実行) ``` $ rails g migration addColumnToUsers ``` ### 6. migrationファイルに下記を追加 ```:20191104093319_add_column_to_users.rb=1 class AddColumnsToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :postcode, :integer add_column :users, :prefecture_code, :integer add_column :users, :address_city, :string add_column :users, :address_street, :string add_column :users, :address_building, :string end end ``` ``` $ rails db:migrate ``` ### 7. models/user.rb に下記を追加 ```:models/user.rb=7 #2019.11.15 以下をコメントアウトにするとprefecture_nameでカラムにデータが入った #include JpPrefecture #jp_prefecture :prefecture_code def prefecture_name JpPrefecture::Prefecture.find(code: prefecture_code).try(:name) end def prefecture_name=(prefecture_name) self.prefecture_code = JpPrefecture::Prefecture.find(name: prefecture_name).code end ``` ### 8. assets/javascripts/welcome.coffeeに下記を追加 ```:assets/javascripts/welcome.coffee=1 $ -> $("#user_postcode").jpostal({ postcode : [ "#user_postcode" ], address : { "#user_prefecture_code" : "%3", "#user_address_city" : "%4", "#user_address_street" : "%5%6" "#user_address_building": "%7" } }) ``` ### 9.views/devise/registrations/edit.html.erbを下記に追加 ```:views/devise/registrations/edit.html.erb=34