Wednesday, September 28, 2011

Rails Thinking Sphinx

Here i'm gonna explain you how to use thinking sphinx in rails application.
this can be done in 5 steps 
step 1:  install the gem thinking sphinx.
           i have installed through terminal ( ubuntu linux ) by typing 
           " sudo gem install thinking-sphinx "
           this will install the gem for you.
           include this gem in gem file of your rails application.
           i.e gem 'thinking-sphinx'
           now run bundle install.
step 2:  open the model file for which you want to add search module.
           here i'm taking an example model  " student "
           in this model file student.rb we have two fields 
           1.name
           2.school
           here we are making search on this two fields " name " and " school ". 
           now, add this code in student.rb file
#################################################################################
              define_index do
                  indexes :name
                  indexes :school
              end
#################################################################################
           here we are telling the thinking-sphinx gem to make indexing on these two fields.
step 3:  open the controller file i.e students_controller.rb 
           go to " index " method 
           here basically you will have 
           " @students = Student.all "
           now change this to 
           " @students = Student.search params[:search] "
           here we are adding parameter "search " to make search on the model student.
step 4:  open the view file of index method i.e index.html.erb
           add this form in it
#################################################################################
                            <%= form_tag students_path, :method => :get do  %>
                                   <p>
                                         <%= text_field_tag :search  % >                              
                                   </p>
                                  <p class="button">
                                         <%= submit_tag "Search" %>
                                 </p>
                            <% end %>
#################################################################################
            here we are adding search field to input search request and return the result.
step 5: open terminal and start thinking sphinx indexing by typing
              " rake ts:index "
           next, start thinking sphinx server by typing 
              " rake ts:start "
           you can stop thinking sphinx by typing
             " rake ts:stop "
start you rails server and check it out.
Note: unless you start thinking sphinx server you cant even view page.
thats it. 
was this helpfull please let me know if you have queries.
please post comments and let me know some feedback. 


  

1 comment: