connect2good/c2g-beta — pull request #2 by mddenton (2014-04-12 22:26:38+00:00)
Title: Add pg-search to Models

TODO

When Individual logs in through Shop button, there is still no search bar to search through merchandises

THINKING:
On Console, am able to search through Merchandise, Need and Organization(by name). However, I was only able to implement the associated_against feature of pg_search on Needs (against Organization). Assoicated_against allows you to search columns on associated models.

From the documentation of pg_search

You can pass a Hash into the :associated_against option to set up searching through associations. The keys are the names of the associations and the value works just like an :against option for the other model. Right now, searching deeper than one association away is not supported. You can work around this by setting up a series of :through associations to point all the way through.

class Cracker < ActiveRecord::Base
has_many :cheeses
end

class Cheese < ActiveRecord::Base
end

class Salami < ActiveRecord::Base
include PgSearch

belongs_to :cracker
has_many :cheeses, :through => :cracker

pg_search_scope :tasty_search, :associated_against => {
:cheeses => [:kind, :brand],
:cracker => :kind
}
end

salami_1 = Salami.create!
salami_2 = Salami.create!
salami_3 = Salami.create!

limburger = Cheese.create!(:kind => "Limburger")
brie = Cheese.create!(:kind => "Brie")
pepper_jack = Cheese.create!(:kind => "Pepper Jack")

Cracker.create!(:kind => "Black Pepper", :cheeses => [brie], :salami => salami_1)
Cracker.create!(:kind => "Ritz", :cheeses => [limburger, pepper_jack], :salami => salami_2)
Cracker.create!(:kind => "Graham", :cheeses => [limburger], :salami => salami_3)

Salami.tasty_search("pepper") # => [salami_1, salami_2]