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

Rails postgres hstore - how to ommit a nil input value from hash


I have a form that displays inputs based on user preferences. I am storing the values as an hstore hash since I dont know ahead of time exactly what the form input for each user will be. The problem I am running in to is that even though a user has an input preferenced doesnt mean they have to enter a value for it each time. Which, can result in :foo => "".

All the doc examples show you how to find records you know the key name of. In my case, I dont know the key name...I need to find all the keys in a hash whose value => "".

Then, I should be able to do something like the docs shows...for each empty value

person.destroy_key(:data, :foo).destroy_key(:data, :bar).save

avals(hstore) is likely what I need to user... How do you use avals with rails?


Solution

  • Since hstore is just a hash in rails...you just need to evaluate the hash before saving it.

    ...in model

      before_save :remove_blanks
    
      private
    
      def remove_blanks
        self.hstore = self.hstore.reject{ |k,v| v.blank? }
      end
    

    replace 'hstore' with your hstore column name