Ruby on Rails: Search Form - Multiple Search Fields

I am trying to create an application that allows a user to search a database. The layout of the search page will behave with some drop-down menus that will show the data already in the database to narrow the search, as well as text fields that allow the user to enter keywords such as "project name". I had a problem getting rails to take all the information that was entered into the search form and do one big search.

Here is part of my search layout:

<%= form_tag search_path, :method => 'get' do %>

<%= hidden_field_tag :direction, params[:direction] %>
 <%= hidden_field_tag :sort, params[:sort] %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search Project Name", :project_name => nil %>
</p>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search Client", :client => nil %>
</p>
<% end %> 

Here are my pointers and search actions in the project controller:

def index
@projects = Project.all

respond_to do |format|
  format.html # index.html.erb
  format.json { render :json => @projects }
 end
end

def search

@project_search = Project.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 5, :page => params[:page])


end

and here is part of my model / project.rb file

def self.search(search)
if search
  where('project_name LIKE ?', "%#{search}%") || where('client LIKE ?', "%#{search}%")
else
  scoped
end
end

, project_name, . , .

, , , .

ROR, , - . .

!

+4
2

: Ruby on Rails:

, @Chris Wise , projects: project_name client.

, , , client Project, . , :

:

def self.search search_term
  return scoped unless search_term.present? 
  where(['client_name LIKE ?', "%#{search_term}%"]) #client_name means the column name, change it to the correct name.
end

:

def self.search search_term
  return scoped unless search_term.present? 
  where(['project_name LIKE ?', "%#{search_term}%"]) #project_name means the column name, change it to the correct name.
end

:

<%= form_tag projects_path, method: :get do %>
  <%= text_field_tag :project_name, params[:project_name] %>
  <%= text_field_tag :client, params[:client] %>
  <%= submit_tag "Search", name: nil %>
<% end %>

:

#return all projects that match the search criteria
@project_search = Project.search(params[:project_name]).all
#return all clients that match the search criteria
@clients_search = Client.search(params[:client]).all

, ...

+3

, , , . -, , .

, :

<%= form_tag search_path, :method => 'get' do %>

<%= form_tag projects_path, :method => 'get' do %>

index.

.

Project :

def self.search search_term
  return scoped unless search_term.present?
  where(['project_name LIKE ? OR client LIKE ?', "%#{search_term}%", "%#{search_term}%"])
end

, :

@projects = Project.search(params[:search]).all

, , , .

+4

All Articles