madeintandem / hstore_accessor

Adds typed hstore-backed field support to ActiveRecord models.
MIT License
242 stars 47 forks source link

Equivalent to ActiveRecord::Store stored_attributes #64

Open brianlittmann opened 9 years ago

brianlittmann commented 9 years ago

In case someone comes looking for it, here is the equivalent of getting the list of attributes (keys) for a given hstore. It's briefly mentioned in the README (bottom paragraph), but wasn't initially clear for me.

# ActiveRecord::Store
class Event < Content
    store_accessor :mydata, :name, :cost, :sponsor
end

Event.stored_attributes[:mydata]
# => [:name, :cost, :sponsor]
# Hstore Accessor gem
class Event < Content
    hstore_accessor :mydata, name: :string, cost: :string, sponsor: :string
end

Event.hstore_metadata_for_mydata.keys
# => [:name, :cost, :sponsor]

For STI cases, I added a method on the parent class to get the keys and fail safely if a child class does not have any hstore attributes defined.

class Content < ActiveRecord::Base
    def self.mydata_attribute_names
        self.hstore_metadata_for_mydata.keys rescue []
    end
    delegate :mydata_attribute_names, to: :class
end