Current version: macOS Catalina 10.15.3
I implemented address autofill in Ruby on Rails. Describe as a memorandum. I hope you find it helpful.
(1) First, download the js file (jQuery plug-in) from the following. jquery.jpostal.js
(2) Place the downloaded js file in app / assets / javascripts.
(3) After adding the following to the Gemfile, `$ bundle install`
in the terminal.
Gemfile
#To be able to use jQuery with Rails
gem 'jquery-rails'
#Address function
gem 'jp_prefecture'
(4) After adding the following column to the User model, `` `$ rails db: migrate``` in the terminal.
Terminal
rails generate migration AddColumnsToUsers postal_code:string prefecture_code:string address_city:string address_street:string
(5) Add the following to app / models / user.rb to edit the User model.
user.rb
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
(6) Add the following to the view to be displayed (This article is implemented on the new member registration screen by introducing devise) Additional description in app / views / devise / registrations / new.html.erb
ruby:new.html.erb
<%= f.label :Postal code%>
<%= f.text_field :postal_code, autocomplete: "postal_code", id: "customer_postal_code" %>
<%= f.label :Prefectures%>
<%= f.collection_select :prefecture_code, JpPrefecture::Prefecture.all, :name, :name, autocomplete: "prefecture_code", id: "customer_prefecture_code" %>
<%= f.label :Municipality%>
<%= f.text_field :address_city, autocomplete: "address_city", id: "customer_address_city" %>
<%= f.label :Street Bunch%>
<%= f.text_field :address_street, autocomplete: "address_street", id: "customer_address_street" %>
(7) Described in app / assets / javascripts / user.coffee to call the jpostal method.
user.coffee
$ ->
$("#user_postcode").jpostal({
postcode : [ "#user_postcode" ],
address : {
"#user_prefecture_code" : "%3",
"#user_address_city" : "%4",
"#user_address_street" : "%5%6%7"
}
})
#Input item format
# %3 prefectures
# %4 municipalities
# %5 town area
# %6 Address of large office
# %7 Name of large office
(8) Additional description below in app / controllers / users_controller.rb
users_controller.rb
private
def user_params
params.require(:user).permit(:postcode, :prefecture_code, :address_city, :address_street) #Columns that allow storage
end
After entering the zip code, the address will be entered automatically.
If the postal code is not automatically entered unless you switch to the screen where the address auto-fill is set and reload it, adding data: {"turbolinks" => false} to the link description solved the problem.
<%= link_to 'Member registration', '/customers/sign_up', data: {"turbolinks" => false} %>
It took about 20 minutes to implement it for the first time. We hope for your reference.
Recommended Posts