Skip to content

Instantly share code, notes, and snippets.

@stujo
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stujo/3138e9b58af60d90814e to your computer and use it in GitHub Desktop.
Save stujo/3138e9b58af60d90814e to your computer and use it in GitHub Desktop.
Ruby on Rails 4.1 : Adding a Search Form using a Form Object
class SearchController < ApplicationController
skip_before_filter :verify_authenticity_token
def results
@search_form = SearchForm.new(params.require(:search_form).permit(:q))
if (@search_form.valid?)
# This sample assumes a model called Contacts with a column field called name
@results = @search_form.search_within (Contacts.all, :name)
end
end
end
class SearchForm
include ActiveModel::Model
#Generic Search Parameter
attr_accessor :q
validates_length_of :q, minimum: 3, message: 'Please enter at least 3 letters to search'
# Add your other search params or validations here
def persisted?
false
end
def search_within scope, column_name
#example where scope: only added when the q param is present
unless self.q.blank?
scope = scope.where(column_name: self.q)
end
#Add your own filters here
scope
end
end
<%= form_for(@search_form, url: search_results_path, method: :get, authenticity_token: false) do |f| %>
<div class="input-group">
<%= f.text_field :q, class: 'form-control', placeholder: 'Name Search' %>
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
<% end %>
<hr/>
<% if @results %>
<%# A functional but unappealing results view %>
<div class="results">
<% @results.each do |result| %>
<div>
<%# Customize this based on your model class %>
<%= link_to result.name, result %>
</div>
<% end %>
</div>
<% elsif %>
<div class="no-results">No Matching Results</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment