$ rails new myapp #myappのところには自由に名前を入れる
gem 'sqlite3', '~> 1.3.13' #sqlite3には ~> 1.3.13を足す
gem 'devise'
gem 'jp_prefecture'
gem 'jquery-rails' #rails5はこれを入れないとjQueryが動かない
7
8
9
10
11Gemfile $ bundle install
$ rails g devise:install
$ rails g devise User
$ rails g devise:controllers users
$ rails g devise:views
Rails.application.routes.draw do
devise_for :users, :controllers => {
:registrations => 'users/registrations',
:sessions => 'users/sessions'
}
end
1
2
3
4
5
6
7routes.rb $ rails g controller welcome index
Rails.application.routes.draw do
root 'welocome#index' #追加
devise_for :users, :controllers => {
:registrations => 'users/registrations',
:sessions => 'users/sessions'
}
end
1
2
3
4
5
6
7routes.rb $ rails g migration addColumnToUsers
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
1
2
3
4
5
6
7
8
920191104093319_add_column_to_users.rb $ rails db:migrate
#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
7
8
9
10
11
12
13
14
15
16
17
18models/user.rb $ ->
$("#user_postcode").jpostal({
postcode : [ "#user_postcode" ],
address : {
"#user_prefecture_code" : "%3",
"#user_address_city" : "%4",
"#user_address_street" : "%5%6"
"#user_address_building": "%7"
}
})
1
2
3
4
5
6
7
8
9
10assets/javascripts/welcome.coffee<div class="field">
<%= f.label :postcode %><br />
<%= f.text_field :postcode, autofocus: true, autocomplete: "postcode" %> </div>
<div class="field">
<%= f.label :prefecture_code %><br />
<%= f.collection_select :prefecture_code, JpPrefecture::Prefecture.all, :code, :name %>
</div>
<div class="field">
<%= f.label :address_city %><br />
<%= f.text_field :address_city, autofocus: true, autocomplete: "address_city" %>
</div>
<div class="field">
<%= f.label :address_street %><br />
<%= f.text_field :address_street, autofocus: true, autocomplete: "address_street" %>
</div>
<div class="field">
<%= f.label :address_building %><br />
<%= f.text_field :address_building, autofocus: true, autocomplete: "address_building" %>
</div>
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52views/devise/registrations/edit.html.erb git clone url
assets/javascripts/jquery.jpostal.jsurl の部分に(https://github.com/ninton/jquery.jpostal.js/)を入れる。クローンしたらassets/javascripts/直下にjquery.jpostal.jsファイルのみを配置する。
不明点、修正点ございましたらコメントよろしくお願いします。