Search code examples
ruby-on-railspostgresqlpg-search

Limit pg_search to the associations of an individual User object


For example:

class User < ActiveRecord::Base
  has_many :cars
end

#  name       :string(255)
class Car < ActiveRecord::Base
  belongs_to :user
end

How would you use pg_search to do a full text search of the names of cars that only a single User instance has (versus all cars)?


Solution

  • I'm the author of pg_search. It sounds like what you want to do is chain a pg_search_scope onto an association:

    class User < ActiveRecord::Base
      has_many :cars
    end
    
    class Car < ActiveRecord::Base
      include PgSearch
      belongs_to :user
      pg_search_scope :search_by_name, against: :name
    end
    
    user = User.find(1)
    user.cars.search_by_name("Ford")