[Ruby on Rails] Automatically enter the address from the zip code

Target

map.gif

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

Created a homes controller and described the following.

config/routes.rb


root 'homes#top'
get 'mypage', to: 'homes#mypage'

app/controllers/homes_controller.rb


class HomesController < ApplicationController
 def top
 end
 def mypage
 end
end

flow

1 In devise, enter the address to enable login 2 Introduced gem'jp_prefecture' and gem'jquery-rails' 3 Introduced jquery.jpostal.js 4 Edit application.js

1. Login with devise

-Reference: See here for details.

Gemfile


gem 'devise'

Terminal


$ bundle install
$ rails g devise:install
$ rails g devise User

Added the following description.

db/migrate/xxxxxxxxxxxxx_devise_create_users.rb


...

<--from here-->
      t.integer :postal_code, null: false
      t.string :prefecture_code, null: false
      t.string :city, null: false
      t.string :street, null: false
      t.string :other_address #Null because there may be no address after the street address:do not add false
<--Add up to here-->
      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

devise:controller

Terminal


rails g devise:controllers users

app/controllers/users/registrations_controller.rb


# frozen_string_literal: true

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  # before_action :configure_account_update_params, only: [:update]

...

  # protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:email, :postal_code, :prefecture_code, :city, :street, :other_address])
  end

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_account_update_params
  #   devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
  # end

  # The path used after sign up.
  def after_sign_up_path_for(resource)
    mypage_path
  end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end
end

devise:model Added the following description to prevent non-input.

app/models/user.rb


  validates :postal_code, presence: true
  validates :prefecture_code, presence: true
  validates :city, presence: true
  validates :street, presence: true

devise:routing

config/routes.rb


Rails.application.routes.draw do
  devise_for :users, controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations',
  }

  root 'homes#top'
  get 'mypage', to: 'homes#mypage'
end

devise:view

Terminal


$ rails g devise:views users

Described in form_for.

erb:app/views/devise/registrations/new.html.erb



form_for...

  <div class="field">
    <%= f.label :postal_code %><br>
    <%= f.text_field :postal_code %>
  </div>

  <div class="field">
    <%= f.label :prefecture_code %><br>
    <%= f.collection_select :prefecture_code, JpPrefecture::Prefecture.all, :name, :name %>
  </div>

  <div class="field">
    <%= f.label :city %><br>
    <%= f.text_field :city %>
  </div>

  <div class="field">
    <%= f.label :street %><br>
    <%= f.text_field :street %>
  </div>
  <div class="field">
    <%= f.label :other_address %><br>
    <%= f.text_field :other_address %>
  </div>


...

This completes the new registration screen for entering the address.

2. Addition of gem

Gemfile


gem 'jp_prefecture' #A gem that converts a prefecture name from a prefecture code
gem 'jquery-rails' #A gem that enables jQuery in Rails

Terminal


$ bundle install

3. Introduced jquery.jpostal.js

https://github.com/ninton/jquery.jpostal.js/ After transitioning to the above URL, press the green "Code" tab and Download the zip file in the red circle. スクリーンショット 2020-09-11 15.20.22.png After unzipping, find the "jquery.jpostal.js" file and Store this file under app / assets / javascripts.

4. Edit application.js

app/assets/javascripts/application.js


//= require rails-ujs <--Delete
//= require jquery <--add to
//= require jquery_ujs <--add to
//= require activestorage
//= require turbolinks
//= require jquery.jpostal <--add to
//= require_tree .

$(function() {
  $(document).on('turbolinks:load', () => {
    $('#user_postal_code').jpostal({
      postcode : [
        '#user_postal_code'
      ],
      address: {
        "#user_prefecture_code": "%3", // #The prefecture is entered
        "#user_city"           : "%4%5", // #The city and town area are entered
        "#user_street"         : "%6%7" // #The address and name of the large office are entered
      }
    });
  });
});


// #Input item format
// #   %3 prefectures
// #   %4 municipalities
// #   %5 town area
// #   %6 Large office address ex)100-6080
// #   %7 Name of large office
When it doesn't work Probably because the behavior of turbolinks is strange. to link_to before link data: {"turbolinks"=>false} You may be able to solve it by writing.

Add the following content to the top

erb:app/views/devise/registrations/new.html.erb


<script type="text/javascript" src="//jpostal-1006.appspot.com/jquery.jpostal.js"></script>

reference

-I made a gem that deals with prefectures called jp_prefecture

Recommended Posts