ほとんど更新のない都道府県のデータなどを管理したいと思った時に、constファイルに書いておくには量が膨大すぎるなぁと思っていました。その時にactive_hashを知りました。
とある案件でpadrinoを使っているのですが、actice_recordは使ってないんだけども”active_hash”を導入してみる
Gemfileにこれを追加
[shell]
gem ‘actice_hash’
[/shell]
bundle install を忘れずに
[code gutter=”false”]
[dosukoi] ~/work/web.egg% bundle install
Installing active_hash 1.4.1
[/code]
早速modelを作成します。
[code lang=”rails”]
class Prefectures < ActiveHash::Base
self.data = [
{ :id => 1, :name => "北海道"},
{ :id => 2, :name => "青森県"},
{ :id => 3, :name => "岩手県"},
{ :id => 4, :name => "宮城県"},
{ :id => 5, :name => "秋田県"},
{ :id => 6, :name => "山形県"},
{ :id => 7, :name => "福島県"},
{ :id => 8, :name => "茨城県"},
{ :id => 9, :name => "栃木県"},
{ :id => 10, :name => "群馬県"},
{ :id => 11, :name => "埼玉県"},
{ :id => 12, :name => "千葉県"}
]
end
[/code]
んで、こうやったら引ける
[shell]
pref = Prefectures.find( id )
puts pref.name
[/shell]
詳しくはこちらをご参考に
コメントを残す