nilify_blanks icon indicating copy to clipboard operation
nilify_blanks copied to clipboard

Support for postgres array and hstore columns

Open espen opened this issue 10 years ago • 6 comments

Example array attribute: :column => ["", ""] should result in nil. :column => ["hello", ""] should result in ["hello"].

espen avatar Aug 08 '14 15:08 espen

So this works when the attribute is an Array. I am however a bit unsure how to test this as Array is only supported by postgresql.

   def nilify_blanks
      (self.nilify_blanks_columns || []).each do |column|
        value = read_attribute(column)
        next unless value.is_a?(String) || value.is_a?(Array)
        if value.is_a?(String)
          next unless value.respond_to?(:blank?)
          write_attribute(column, nil) if value.blank?
        elsif value.is_a?(Array)
          value.reject! { |c| c.blank? }
          if value.empty?
            write_attribute(column, nil) if value.blank?
          else
            write_attribute(column, value) if value.blank?
          end
        else
          next
        end
      end
    end

espen avatar Aug 11 '14 10:08 espen

For those interested I have a fork with support for columns with array and hstore data type here: https://github.com/espen/nilify_blanks. There are some tests but you have to manually change db adapter to postgresql to be able to run them for now.

espen avatar Dec 25 '17 23:12 espen

Hi @rubiety. What's your thoughts on this? About the idea, not the code (can be improved if necessary). I have a fork that I used for a few years now without any problems to address this issue. Now @swrobel is helping out with a new PR to the fork. Would be great to focus the development into the main repo if you think it's a useful addition.

espen avatar Apr 11 '18 10:04 espen

I would definitely support this change and it makes sense to me. I'm certainly open to a solid pull request (sounds like @swrobel is working on one) that implements this.

Because this isn't necessarily postgres-specific, it would be ideal to keep it as generic as possible (reacting to attributes that expose themselves as a Hash or Array, not specific to JSONB or whatever within Postgres).

rubiety avatar Apr 12 '18 21:04 rubiety

🙋🏼‍♂️ just a clarification, I'm not working on a PR, I just submitted a PR to @espen's fork to fix an issue with false being nilified within arrays/hashes. I believe the code is just looking for array/hash types, so it's probably just tests that need work.

swrobel avatar Apr 12 '18 21:04 swrobel

Same issue here, would really appreciate this :D Atm, we're manually removing blanks for those fields.. :/

What about booleans? Same issue for us there...

Our record changes (with logidze gem) gives us:

AGENT_APPROVED changed from nil to ""

create_table :users do |t|
  # ...
  t.boolean :agent_approved
end

(Editing records with Active Admin)

Frexuz avatar May 03 '18 11:05 Frexuz