Last active
December 17, 2015 00:59
-
-
Save slawosz/5525555 to your computer and use it in GitHub Desktop.
hstore on rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# all including models requires column named 'data' of type hstore | |
module Extensions | |
module AttributeField | |
extend ActiveSupport::Concern | |
included do | |
class_attribute :attributes | |
self.attributes = Hash.new {|k,v| k[v] = []} | |
end | |
module ClassMethods | |
# data columns keys always as strings! | |
def field(name) | |
self.attributes[self] << name | |
class_eval do | |
define_method name do | |
data[name.to_s] if data.present? | |
end | |
define_method "#{name}=" do |new_value| | |
self.data = {} if data.nil? | |
self.data[name.to_s] = new_value | |
end | |
end | |
end | |
def available_attributes | |
klasses = self.ancestors.select {|klass| klass <= Item} | |
klasses.inject([]) do |memo, klass| | |
memo += attributes[klass] | |
end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Aircraft < AircraftType | |
include Extensions::AttributeField | |
# this will create fields that are stored in hstore column (named data) but accessible as normal AR columns | |
field :serial_number | |
field :registration | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment