thiebo
thiebo

Reputation: 1435

pg_search model and controller relation

This probably is a nooby one. I'm building a search form.

In the model document.rb, I have this :

pg_search_scope :search_full_text, 
                :against => :full_text, 
                :using => {
                    :tsearch => {
                        :prefix => true
                        }
                    }

and in documents_controller.rb, I have :

def find
    $results = Document.search_full_text(params[:ch_acte][:text])
end

But NOTHING gets send to the database. The server log only says:

Started POST "/documents/find" for ::1 at 2017-01-19 08:48:07 +0100
Processing by DocumentsController#find as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZkqVYMuqMqnUjLer/FVdBdtv4cycp71dXqPQw6j0mfHKX5ptin7p7YiYFj8bNtjciQDmHzbKtBnZoILpGGvl8Q==", "ch_acte"=>{"text"=>"complet", "words"=>"", #[cut for brievity]}, "commit"=>"Cherche"}
Rendering documents/find.html.erb within layouts/messources
Rendered documents/find.html.erb within layouts/messources (0.4ms)
Completed 200 OK in 216ms (Views: 210.2ms | ActiveRecord: 0.0ms)

Other than the method pg_search_scope in the model and calling that method in the controller, what must I do to get this sent to the database?

When I run Document.search_full_text("esp") in rails console, it works fine.

UPDATE

I added this in documents/find.html.erb :

<% $results.each do |m| %>
    <p>The id is <%= m.id %>.</p>
<% end %>

I get an page that displays my menu, and only white after that...

Upvotes: 0

Views: 474

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You should understand that Rails tries to be as performant as possible. When you build a search it does NOT execute until you attempt to access the results of the search.

So you would do...

def find
  @documents = Document.search_full_text(params[:ch_acte][:text])
end

Then in your find.html.erb you might do...

<% @documents.each do |document| %>
  <%= document.name %>
<% end %>

The query is only executed when the @documents.each line is executed to retrieve the documents... i.e. only when it needs to be executed.

Upvotes: 3

Related Questions