1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ROR jp_prefectureとjpostalで郵便番号から住所を自動入力する

Last updated at Posted at 2021-10-18

jp_prefectureとjpostalで住所自動入力を追加しました。

新規にデータを作成する際、住所を自動で入力できると楽だなと思い、使ってみました。
最初なので少しわたわたしたけど、思ったよりは簡単

jQueryの導入

rails6はjquery-railsではなく、yarnから導入する

ターミナル
yarn add jquery

environment.jsに設定を追加

config/webpack/environment.js
const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

jqueryをimportする

app/javascript/packs/application.js
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
import "jquery"

Rails.start()
Turbolinks.start()
ActiveStorage.start()

jp_prefectureの導入

都道府県コードと都道府県名を変換

Gemfile
gem 'jp_prefecture'
ターミナル
bundle install

jpostalを導入

HPからZIPファイルをダウンロード
jquery.jpostal.js-masterフォルダ内のjquery.jpostal.jsapp/javascript/packs配下に保存する。

packs/jquery.jpostal.jsをimportする。
jpostalを使用するように編集する。

app/javascript/packs/application.js
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
import "jquery"
import "packs/jquery.jpostal.js"

Rails.start()
Turbolinks.start()
ActiveStorage.start()

jQuery(document).on("turbolinks:load", function() {
  $('#institution_postcode_text').jpostal({
    postcode : [
      // 取得する郵便番号のテキストボックスをidで指定
      '#institution_postcode_text'
    ],
    address: {
      // %3 => 都道府県、 %4 => 市区町村 %5 => 町域 %6 => 番地 %7 => 名称
      // それぞれを表示するコントロールをidで指定
      "#institution_prefecture"  : "%3",
      "#institution_city_text"   : "%4%5",
      "#institution_street_text" : "%6%7"
    }
  });
});

viewの設定

new.html.erb
<div class="institution_new_main">
  <div class="institution_new_container">
    <h2>医療機関情報新規作成</h2>
    <%= form_with model: @institution do |f| %>
      <%= render "shared/institution_form", f: f %>
      <div class="institution_name_container">
        <%= f.submit "登録する", class: "institution_submit" %>
      </div>
    <% end %>
  </div>
</div>
shared/institution_form
<div class="flex_spaceevenly">
  <div class="institution_show_info_container">
    <div class="institution_show_name_container">
      <div class= "institution_show_name_label show_label">医療機関名</div>
      <div class="institution_show_name_text show_text"><%= institution.name %></div>
    </div>
    <div class="institution_show_department_container">
      <div class= "institution_show_department_label show_label">診療科目</div>
      <div class="institution_show_department_text show_text"><%= institution.department %></div>
    </div>
    <div class="institution_show_postcode_container">
      <div class="institution_show_postcode_label show_label">郵便番号</div>
      <div class="institution_show_postcode_text show_text"><%= institution.postcode.to_s[0,3] %>-<%= institution.postcode.to_s[3..]%></div>
    </div>
    <div class="institution_show_address_container">
      <div class="institution_show_address_label show_label">住所</div>
      <div class="institution_show_address_text show_text", id="institution_mapping_address"><%= institution.address %></div>
    </div>
    <div class="institution_show_intro_container">
      <div class="institution_show_intro_label show_label">紹介</div>
      <div class="institution_show_intro_text show_text"><%= institution.introduction %></div>
    </div>
  </div>
  <div class="institution_show_image_container">
    <% if institution.image? %>
      <%= image_tag institution.image.url, alt: "アイコン画像", class: "institution_show_image" %>
    <% else %>
      <%= image_tag "default_institution_image.png", alt: "アイコン画像", class: "default_institution_show_image" %>
    <% end %>
  </div>
</div>

Schema

schema.rb
create_table "institutions", force: :cascade do |t|
  t.string "name"
  t.string "address"
  t.string "introduction"
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
  t.string "image"
  t.integer "postcode"
  t.integer "prefecture_code"
  t.string "address_city"
  t.string "address_street"
  t.string "address_building"
  t.string "prefecture"
  t.string "department"
end

controllerの設定

controller.rb
def new
  @institution = Institution.new
end

def create
  @institution = Institution.new(institution_params)
  # 住所をつなげてaddressに格納
  @institution.address = @institution.join_address
  if @institution.save
    redirect_to institutions_path, notice: "医療機関を追加しました"
  else
    render "new"
  end
end

def update
  @institution = Institution.find(params[:id])
  if @institution.update(institution_params)
    @institution.address = @institution.join_address
    if @institution.update(institution_params)
      redirect_to institutions_path, notice: "医療機関情報を更新しました"
    else
      render "edit"
    end
  else
    render "edit"
  end
end

private
def institution_params
  params.require(:institution).permit(:name, :postcode, :prefecture, :address_city, :address_street, :address_building, :introduction, :image)
end

modelの設定

rb.model.rb
class Institution < ApplicationRecord
  # 住所をつなげる関数
  def join_address
    "#{self.prefecture}#{self.address_city}#{self.address_street}#{self.address_building}"
  end
end

jQueryが動かない時は

どうしても動かない時は、以下をviewの最初に追加

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

参考資料

【Ruby on Rails】郵便番号から住所を自動入力
【Rails】jpostalとjp_prefectureを用いて住所自動入力の実装
郵便番号から該当する住所を自動で入力できるjQueryプラグイン「jquery.jpostal.js」
【Ruby】f.collection_select を使ってみた
【Rails】 form_withの使い方を徹底解説!
Railsのモデルに書いたメソッドってどうやってコントローラで使うの?

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?