Rails Admin で、ある条件ではドロップダウン リストを表示し、それ以外の場合は文字列フィールドを表示するフィールドを実装するにはどうすればよいですか?
概要
:value フィールドに次のロジックを実装しようとしています。 :key == “test” の場合、2 つのオプション [‘option1’、’option2] を含むドロップダウン リストが表示されます。 それ以外の場合は、通常の行フィールドが表示されます。
私は次のようなことを期待していました:
#Table name: settings
#key :string
#value :string
class Setting < ApplicationRecord
extend Enumerize
rails_admin do
edit do
field :value do
formatted_value do
if bindings[:object].key == "test"
enum do
['option1', 'option2]']
end
else
bindings[:view].text_field(:value, value: value)
end
end
end
end
end
end
ただし、このコードは機能しません (すべてのフィールドに対してドロップダウン リスト [‘option1’, ’option2]’] が表示されます) 次のようなことを試してみました:
bindings[:view].select_tag("value",binding[:view].options_for_select(["1", "2"], value))
しかし、options_for_select のモデルには問題があります。
ビューを編集するのではなく、より良く編集したいと考えています。何かあれば喜んでお手伝いさせていただきます!
解決策
私が見つけた唯一の有効なオプションは、attr_accessor を使用するものです。
#Table name: settings
#key :string
#value :string
class Setting < ApplicationRecord
extend Enumerize
attr_accessor :extra_field
before_save :assign_extra_field_to_value
rails_admin do
edit do
field :value do
visible do
bindings[:object].key != "test"
end
end
field :extra_field, :enum do
label "Value"
visible do
bindings[:object].key == "test"
end
enum do
['option1', 'option2']
end
end
end
end
private
def assign_extra_field_to_value
self.value = extra_field if self.key == "test"
end
end
誰かがもっと良いアイデアを持っているなら、喜んでそれを見てみたいと思います。