Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Demonstrate validation of arbitrary fields (e.g., hstore)

View validator.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#!/usr/bin/env ruby
 
require 'active_record'
 
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
 
ActiveRecord::Schema.define do
create_table :documents, :force => true do |t|
end
end
 
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
 
class Document < ActiveRecord::Base
extend HstoreValidation
 
validates_hstore :data do
validates_length_of :title, :maximum => 50
end
end
 
d = Document.new
d[:data] = {title: 'abc' * 51}
 
p d.valid?
p d.errors
 
d[:data][:title] = 'shorter title'
 
p d.valid?
p d.errors
bezelga commented

by the time, Rails does not have anything built in to validate hstore fields?

Owner
rf- commented

For most use cases, it would be better now to use store_accessor and just write normal validations.

This seems to no longer work on Rails 4.1 ;-(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.