nilify_blanks
nilify_blanks copied to clipboard
Support for postgres array and hstore columns
Example array attribute:
:column => ["", ""]
should result in nil.
:column => ["hello", ""]
should result in ["hello"].
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
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.
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.
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).
🙋🏼♂️ 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.
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)