Created
July 1, 2010 16:41
-
-
Save andreapavoni/460215 to your computer and use it in GitHub Desktop.
Rails3: using Arel to make conditional searches based on conditional params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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