rom-rb / rom

Data mapping and persistence toolkit for Ruby
https://rom-rb.org
MIT License
2.09k stars 161 forks source link

Postgres array as column #362

Closed Fire-Dragon-DoL closed 7 years ago

Fire-Dragon-DoL commented 7 years ago

Hello, I lost countless hours on this, I can't really get postgresql array to work! I'm passing only that field to create : { tags: ["foo", "bar"] }, but I keep getting errors.

I reached a good point, my relation has the tags field like the following:

attribute :tags, pgtypes::Array(:text)

And this works as long as I pass an array of text. However, my tags are an array of symbols, so I was adding a constructor, but no matter what I do, I keep getting NoMethodError: undefined method []' for nil:NilClass

I tried the following strategies:

      attribute :tags, pgtypes::Array(:text).constructor do |input|
        Sequel.pg_array(input.map(&:to_s), :text)
      end
      attribute :tags, pgtypes::Array(:text).constructor do |input|
        input.map(&:to_s)
      end

No matter what, unless I use the "raw" type without constructor, I get that error

Fire-Dragon-DoL commented 7 years ago

Damn I solved this, kept trying. Looks like there were two problems:

1) If you use do/end syntax, ruby thinks the block is for attribute, not constructor 2) You must manually call Sequel.pg_array to make sure the object is converted to the correct format

Ended up with something like

      attribute :tags,               pgtypes::Array.constructor(
        ->(input) { Sequel.pg_array(input.map(&:to_s), :text) }
      )