Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4.1 validation of arbitrary fields via hstore

I use HStore in Rails 4.1 to manage I18n and storage of languages. It works great the only problem I have is I would like to do something like this (instead of using store_accessor)

In Rails 4.0 this worked great:

https://gist.github.com/rf-/2322543 (simple_form and hstore basic functionality)

So I could simple do something like:

  validates_hstore :content do
    validates_presence_of :en
  end

Where the magic happened (doesn't seem to work correctly in Rails 4.1)

module HstoreValidation
  def validates_hstore(field, &block)
    validation_class = Class.new do
      include ActiveModel::Validations

      def self.name
        '(validations)'
      end

      def initialize(data)
        @data = data
      end

      def read_attribute_for_validation(attr_name)
        @data[attr_name]
      end
    end
    validation_class.class_eval &block

    validate do
      validator = validation_class.new(self[field])

      if validator.invalid?
        validator.errors.each do |attr, text|
          self.errors.add(attr, text)
        end
      end
    end
  end
end

Instead i always get, even when the field is not blank:

messages:
  :en:
  - can't be blank
like image 602
holden Avatar asked Sep 11 '14 09:09

holden


1 Answers

it happens because hstore key/values are converted to strings, and when validation tries to validate attribute :en it always will be nil, so you could replace your read_attribute_for_validation method to:

def read_attribute_for_validation(attr_name)
  @data[attr_name.to_s]
end

note: attr_name.to_s



also you could use store_accessor like:

store_accessor :content, :en

validates :en, presence: true
like image 82
Igor Guzak Avatar answered Oct 07 '22 00:10

Igor Guzak