あまり無いケースだとは思うが、enumからセレクトボックスを作成する際に、文言を変えたい場合の方法をメモしておく。
前提として、gemに enumerize
と reform
を使用している。
product_form.rb
extend Enumerize
enumerize :fluit, in: {
apple: 1,
orange: 2,
peach: 3,
strawberry: 4,
cherry: 5,
}, predicates: { prefix: true }
property :fluit
ja.yml
product:
fluit:
apple: りんご
orange: オレンジ
peach: もも
strawberry: いちご
cherry: さくらんぼ
普通に書けば、これで良い。
new.slim
= f.select :fluit, f.object.class.fluit.options, {prompt: '果物を選択'}
しかし、「『りんご』と『さくらんぼ』は『(特別セール中)』という文言を入れたい」と言われたとする。
とはいえ、ja.ymlを変えたくはない。
f.object.class.fluit.options
を使わずに1つずつ書くのも、メンテナンス性が悪い。
そこで、f.object.class.fluit.options
が生成する Array を map で回して、特定の value の時のみ、文言を足して返すメソッドを作った。
product_form.rb
def fruit_select_display
self.class.fluit.options.map do |key, value|
if value == 'apple' || value == 'cherry'
[key + '(特別セール中)', value]
else
[key, value]
end
end
end
new.slim
= f.select :fluit, f.object.fruit_select_display, {prompt: '果物を選択'}
これでいったん用は足せた。