Skip to content

Instantly share code, notes, and snippets.

@andreapavoni
Created July 1, 2010 16:41
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 andreapavoni/460215 to your computer and use it in GitHub Desktop.
Save andreapavoni/460215 to your computer and use it in GitHub Desktop.
Rails3: using Arel to make conditional searches based on conditional params
<div id="searchform">
<%= form_tag search_people_path, :method => 'get' do |f| %>
<div class="field">
<%= label :search, :firstname, 'Firstname' %><br/>
<%= text_field :search, :firstname %>
</div>
<div class="field">
<%= label :search, :lastname, 'Lastname' %><br/>
<%= text_field :search, :lastname %>
</div>
<%= submit_tag "Search" %>
<% end %>
</div>
class PeopleController < ApplicationController
# ... other CRUD actions ...
def search
q = Person.arel_table # initialize Arel table
@people = Person.order(:created_at) # start with a simple option
@search = Search.new(params[:search]) # initialize Search model with the search params
# apply conditions only if they are present
@people = @people.where(q[:lastname].matches("%#{@search.lastname}%")) if @search.lastname
@people = @people.where(q[:firstname].matches("%#{@search.firstname}%")) if @search.firstname
render :index # render index action, it's the same output, just filtered by conditions passed
end
end
# put this in app/models/search.rb
class Search
attr_accessor :attributes
def initialize(attributes = {})
@attributes = attributes
@attributes.each do |k,v|
self.class.send(:define_method,k) { v }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment