DaveR
DaveR

Reputation: 2483

Storing booleans in Active Record Store

I am using a standard rails form to update an ActiveRecord::Store

  store :settings, accessors: %i[is_public]

My form looks like this:

<%= form.select(:is_public, options_for_select([['True', true], ['False', false]])) %>

When I look at the saved hash these have been converted to strings, is there a way to preserve the boolean type here?

Upvotes: 0

Views: 522

Answers (1)

DaveR
DaveR

Reputation: 2483

I was able to write a CustomStoreAccessor module to overwrite the accessor for these attributes:

module CustomStoreAccessor
  def boolean_store_accessor(attr_name)
    define_method "#{attr_name}=" do |value|
      super(value=='true')
    end

    define_method attr_name do
       super()=='true'
    end
  end

  def integer_store_accessor(attr_name)
    define_method "#{attr_name}=" do |value|
      super(value.to_i)
    end

    define_method attr_name do
      super().to_i
    end
  end
end

This then allows me to add these methods to my model:

class Client < ApplicationRecord
  extend CustomStoreAccessor
  store :settings_object, accessors: %i[is_public max_sessions]
  boolean_store_accessor :is_public
  integer_store_accessor :max_sessions

Upvotes: 1

Related Questions