LoginSignup
8
8

More than 5 years have passed since last update.

都道府県マスターでJpPrefectureを利用したモデルに複数の都道府県コードが含まれてる場合の県名表示をどうするか

Posted at

はじめに

都道府県の情報を持ちたい場合に、都道府県のマスターでJpPrefectureのようなgemを使うかと思います。

単純に都道府県のコードが1つだけというモデルの場合には公式のREADMEを読めばすぐにわかると思います。

出発地と到着地みたいな情報を管理する機能を実装する時に都道府県のコードが2つになる場合にどのようにJpPrefectureを利用すればいいのかすぐにわからなかったので自分のメモとして書いておきます

やり方

公式のREADMEに

生成されるメソッド名は method_name というオプションで指定することができます:

という記述があったので、試しに以下のように出発地の都道府県のID(from_prefecture_id)と到着地の都道府県のID(to_prefecture_id)に対してそれぞれmethod_nameを定義します

# == Schema Information
#
# Table name: tours
#
#  id                 :integer          not null, primary key
#  from_prefecture_id :integer
#  to_prefecture_id   :integer
#  created_at         :datetime         not null
#  updated_at         :datetime         not null
#

class Tour < ActiveRecord::Base

  include JpPrefecture
  jp_prefecture :from_prefecture_id, method_name: :from_prefecture
  jp_prefecture :to_prefecture_id, method_name: :to_prefecture

end

こうすることで


tour = Tour.first
tour.from_prefecture
=> #<JpPrefecture::Prefecture:0x007fc444e86b28
 @area="北海道",
 @code=1,
 @name="北海道",
 @name_e="Hokkaido",
 @name_h="ほっかいどう",
 @name_k="ホッカイドウ",
 @zips=[10000..70895, 400000..996509]>
tour.to_prefecture
=> #<JpPrefecture::Prefecture:0x007fc4443a58a8
 @area="東北",
 @code=2,
 @name="青森県",
 @name_e="Aomori",
 @name_h="あおもりけん",
 @name_k="アオモリケン",
 @zips=[185501..185501, 300111..395346]>

みたいなことが実現できました。

8
8
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
8
8