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])
Problem solved in another question: Ruby on Rails: Advanced search
I have never used the gem ransack
, but I think your first line def search
should be def index
and than you define the search method
somewhere else... or have you included a route for search
in 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
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
products_controller.rb:
def index
@projects = Project.search(params[:search])
end
The search form can be included anywhere in your application:
<% form_tag projects_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
Please take a look here and if you need an advanced search look here.
I hope it helps