marcamillion
marcamillion

Reputation: 33755

How do I specify an `associated_against` an association that has an `as: ` name in pg_search?

Ok, so I have a Node model that has these associations:

class Node < ActiveRecord::Base
  belongs_to :family_tree
  belongs_to :user
  belongs_to :media, polymorphic: true, dependent: :destroy
  has_many :comments, dependent: :destroy
end

The key association is the media one, which is really an association to Video. This is how my Video model looks:

class Video < ActiveRecord::Base
  has_one :node, as: :media
end

But I can't quite figure out how to specify this in my pg_search_scope.

I have tried this:

  include PgSearch
  pg_search_scope :node_search, against: [:name, :user_id, :circa, :cached_user_tag_list, :cached_tagged_user_names],
    using: { tsearch: { any_word: true, dictionary: :english, prefix: true} },
    :associated_against => {
      video: [:description, :title]
    }

But the error I get is this:

Completed 500 Internal Server Error in 131ms (ActiveRecord: 41.6ms)    
NoMethodError - undefined method `table_name' for nil:NilClass:

So when I try this way:

  include PgSearch
  pg_search_scope :node_search, against: [:name, :user_id, :circa, :cached_user_tag_list, :cached_tagged_user_names],
    using: { tsearch: { any_word: true, dictionary: :english, prefix: true} },
    :associated_against => {
      media: [:description, :title]
    }

I get this error:

Completed 500 Internal Server Error in 126ms (ActiveRecord: 17.7ms)    
NameError - uninitialized constant Node::Media:

How do I specify that association or is this an edgecase that pg_search doesn't know how to manage?

Upvotes: 0

Views: 2143

Answers (1)

KVS
KVS

Reputation: 133

The maintainer of the pg_search has mentioned that polymorphic associations could not be searched directly through SQL, and therefore are not available for pg_search - https://stackoverflow.com/a/15455017.

Upvotes: 2

Related Questions