Skip to content

Instantly share code, notes, and snippets.

@foliwe
Last active March 3, 2017 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foliwe/9967af8829928aa94a3d4f72e4076720 to your computer and use it in GitHub Desktop.
Save foliwe/9967af8829928aa94a3d4f72e4076720 to your computer and use it in GitHub Desktop.
Advanced search Form
class Book < ApplicationRecord
belongs_to :category
def self.search(params)
books = Book.all
books = books.where("title LIKE '?'",params[:search]) if params[:search].present?
books = books.where(category_id: params[:category]).where("price <= ?", params[:price])
end
end
def search
if params[:price].present? && params[:category].present?
@books = Book.search(params)
elsif params[:category].present?
@books = Book.where(category_id: params[:category])
else
@books = Book.all
end
end
end
<%= form_tag search_books_path, method: :get do %>
<%= select_tag :category, options_from_collection_for_select(Category.all, :id, :name), :include_blank => "Select Category" %>
<%=number_field_tag :price%>
<%=text_field_tag :search, nil, placeholder: "search" %>
<%= submit_tag "Search" %>
<%end%><%end%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment