Skip to content

Instantly share code, notes, and snippets.

@lirenyeo
Created May 25, 2022 14:21
Show Gist options
  • Save lirenyeo/9661ee9b6869b800f9db72ad268f948d to your computer and use it in GitHub Desktop.
Save lirenyeo/9661ee9b6869b800f9db72ad268f948d to your computer and use it in GitHub Desktop.
Using Flag ShihTzu with Formtastic

FlagShihTzu + Formtastic + Active Admin

To get all flags available in a model:

User.flag_mapping
User.flag_options
User.flag_columns

To use it with Formtastic

Helper method:

    def flag_to_collection(model, col)
      model.flag_mapping[col.to_s].map do |k, v|
        [k, v]
      end
    end

Using 'access_flags' shihtzu column on User table as example: model/user.rb

  has_flags 1 => :virtual,
            2 => :physical,
            3 => :gala,
            6 => :mte_clinical,
            7 => :mte_lab,
            8 => :mte_nurse,
            9 => :mte_2,
            :column => 'access_flags',
            :bang_methods => true

  def access_flags_array=(val)
    self.access_flags =
      if val.respond_to?(:reduce)
        val.reduce(0) { |memo, n| memo + n.to_i }
      else
        val
      end
  end

  def access_flags_array
    access_flags.to_s(2).split('').reverse
                .map.with_index { |bit, i| 2**i if bit == '1' }
                .compact
  end

form.slim

= f.input :access_flags_array, as: :check_boxes, collection: flag_to_collection(User, 'access_flags')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment