How to implement a field in the Rails Admin that displays a dropdown list under one condition, and a string field otherwise?

72 Views Asked by At

I'm trying to implement the following logic for the :value field: if :key == "test", then a drop-down list with two options ['option1', 'option2] is displayed in any other case, a normal line field is displayed.

I expected something like this:

#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

But this code does not work (for all fields it displays a drop-down list ['option1', 'option2]']) Tried something like this:

bindings[:view].select_tag("value",binding[:view].options_for_select(["1", "2"], value))

But there are problems in model with options_for_select.

I don’t want to edit view, but I want to do it better. I will be glad for any help!

1

There are 1 best solutions below

0
Данил On

The only working option I found is through 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

If someone has a better idea, I would be glad to see it.