Search code examples
ruby-on-rails-3postgresql-9.1hstore

Return an array of uniq keys from a query of hstore data in rails


I would like to use hstore keys as table column headers. My approach is to simply map a rails query that will return all keys from multiple records and then print the uniq ones to the array.

I'll be building the table in Prawn, using both static and dynamic column headers...like this..but, this doesnt work of course.

 [["DATE", "LOCATION", "DAY OFF", "START", "END" + @users_options.select("properties").map { |k,v| ",#{k}" }]]

How can I iterate over the users logs, and output only uniq keys?

I just tried this...seems close...but not working yet

 a = []
 user.useroptions.select(:properties).collect{ |k,v| a << k }

Solution

  • I created a helper method:

    def keys(user)
      keys = []
      user.useroptions.select(:properties).each do |opt| 
        a = opt.properties.keys
        keys << a
      end
    
      keys.flatten.uniq
    end
    

    This iterates through all hstore records, grabs the keys, then flattens the hash, and puts only the uniq values