Search code examples
postgresqlruby-on-rails-5tsvector

Rails activeRecord version for to_tsvector() function of Postgresql


I have a TSVECTOR column in my database and I want to update this column via Rails callback rather than a trigger. I want to know if there's an ActiveRecord code to achieve this. So far I'm doing this by manually executing a raw SQL and it doesn't look nice.

ActiveRecord::Base.connection.execute("update my_table set tsvector_document = to_tsvector('english', #{string_tokens}) where id = #{id}")

I'm wondering if there's a better approach to do this without using a raw SQL.

Thanks in advance.


Solution

  • I ended up using rails' PG Search plugin for this where it handles this TS Vector conversion.

    PgSearch.multisearch_options = {
      using: {
        tsearch: {
          prefix: true,
          dictionary: 'english',
          tsvector_column: 'vector_column_name_here'
        },
        trigram: {
          threshold: 0.2
        }
      }
    }