I’m new to ROR, so this could be a very simple problem.
I have just installed the ransack gem for my web application. I am wanting to search on project names and clients in my database. I have an index page view, which I use for my homepage, then a search page, which uses a search action that I created.
def index
@projects = Project.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @projects }
end
end
def search
@q = Project.search(params[:q])
@project_search = @q.result(:distinct => true)
respond_to do |format|
format.html # search.html.erb
format.json { render :json => @projects }
end
end
Here is part of my search view:
<%= search_form_for @q do |f| %>
<%= f.label :project_name %>
<%= f.text_field :project_name %>
<%= f.label :client %>
<%= f.text_field :client %>
<%= f.submit %>
<% end %>
When I try and load the search page, I get this error:
undefined method `search’
With the extracted source being in my project controller at this line
@q = Project.search(params[:q])
Hopefully it’s an easy fix, and you can explain what I’m doing wrong so I learn.
Any help at all will be appreciated.
Thanks in advance!
EDIT:
I’ve added my index action above to show you that I have an index action, and a search action. Here is my routes.rb file as well.
FinalApp::Application.routes.draw do
resources :projects
match "search" => "projects#search", :as => :search
root :to => 'projects#index'
end
SECOND EDIT:
I hadn’t restarted my server. I now have another error.
undefined method `result’
With the extracted source being in my project controller at this line
@project_search = @q.result(:distinct => true)
THIRD EDIT:
Another error :/
undefined method `schema_cache’
With the extracted source being in my project controller at this line
@q = Project.search(params[:q])
I have never used the gem
ransack, but I think your first linedef searchshould bedef indexand than you define thesearch methodsomewhere else… or have you included a route forsearchin your routes.rb?Anyway, what you are looking for is a very simple search and I don’t think you need any gem for it.
You can define the search method in your model:
product.rb
products_controller.rb:
The search form can be included anywhere in your application:
Please take a look here and if you need an advanced search look here.
I hope it helps