I'm trying to use pg_search to search across two models. I have a 'Hires' model with two columns 'child_id' and 'book_id'. I want to index the child name associated with the child_id in the 'Children' model.
My model looks like this:
Hire.rb
class Hire < ActiveRecord::Base
belongs_to :book
belongs_to :child
accepts_nested_attributes_for :book
accepts_nested_attributes_for :child
include PgSearch
multisearchable :against => [:child_id, child_forename]
def child_forename
child.forename
end
end
but when I try to build the index (rake pg_search:multisearch:rebuild[Hires]) I get the following error:
rake aborted!
NameError: undefined local variable or method `child_forename' for Hire (call 'Hire.connection' to establish a connection):Class
/Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.4/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
/Users/James/Documents/websites/STAlibrary/app/models/hire.rb:12:in `<class:Hire>'
/Users/James/Documents/websites/STAlibrary/app/models/hire.rb:1:in `<top (required)>'
/Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:457:in `load'
How can i build this query to index the child forename?
You are missing a colon in front of child_forename.
You need to pass in symbols:
multisearchable :against => [:child_id, :child_forename]
The given error tells you that the method "child_forename" is not defined. That is because the ruby interpreter reads the file top down and the method is not yet defined at that point. But if it was, the line would evaluate to
multisearchable :against => [:child_id, "Mary"]
which is probably not what you want. If you correctly pass the symbol, the method with that name is called later in some on_update callback when an object is instantiated and the object contents are indexed.