How to configure pg_search multi-user mode for related models in Rails?

I am adding pg_search to a Rails application. I do not quite understand the configuration and would appreciate a gentle push in the right direction.

Firstly, I already have several model sites, more or less configured and working in my application. But I want to expand it to also search on related models.

For example, I have classes of manufacturers, cars, models. Currently, if I'm looking for a Ford, only the manufacturer is returning. I would also like to return all related cars (which belong to the manufacturer) and Models (which belong to Car).

I see how to do this as a cloud search

class Car pg_search_scope :manufactured_by, :associated_against => { :manufacturer => [:name] } end 

But if I try to do it in multi-user mode, it will not work

 class Car include PgSearch multisearchable :against => [:name], :associated_against => { :manufacturer => [:name] } end 

It does not generate an error, it simply does not take related records.

I have a feeling that I am missing something fundamental in my understanding of how it all fits together. I would really appreciate it if someone could help me figure this out or point me to a good source of information. I went through the github info and related Railscast, but I still missed something.

+7
source share
1 answer

Cannot search related records using multisearch due to the way polymorphic associations work in Rails and SQL.

I will add an error explaining the situation, so that in the future it will not be so confusing.

Sorry for the confusion.

Instead, you can define a method in Car that returns the text you want to execute.

 class Car < ActiveRecord::Base include PgSearch multisearchable :against => [:name, manufacturer_name] belongs_to :manufacturer def manufacturer_name manufacturer.name end end 

Or, to be even more concise, you can delegate:

 class Car < ActiveRecord::Base include PgSearch multisearchable :against => [:name, manufacturer_name] belongs_to :manufacturer delegate :name, :to => :manufacturer, :prefix => true end 

But you have to make sure that the pg_search_documents table is updated if you ever made a name change with a manufacturer instance, so you should add :touch => true to your association:

 class Manufacturer < ActiveRecord::Base has_many :cars, :touch => true end 

Thus, it will call Active Record callbacks in all car records when the manufacturer updates, which will call pg_search callback to update the searchable text stored in the corresponding pg_search_documents record.

+12
source

All Articles