Skip to content

search_builder is a rails plugin to generate search form for models easily

Notifications You must be signed in to change notification settings

handlino/search_builder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SearchBuilder Plugin

This plugin provides a flexible way to add conditional search to Rails.

Installation

script/plugin install git://github.com/handlino/search_builder.git

Example Usage

SearchBuilder 是參考http://railscasts.com/episodes/111-advanced-search-form 的作法,利用你原有的model來做搜尋。

Model

假設你有一個model如下:

class Product << ActiveRecord::Base 
end

在products table中有下列欄位:

name :String(255)
price :Float
order_number :Integer
created_at :DateTime

首先,你需要在model中mixin SearchBuilder module:

include SearchBuilder

然後新增一個搜尋的instance method:

def search_all
  Product.find(:all, :conditions => conditions)
end

如果你要針對欄位,作sql like的搜尋你只需要在model中,你可以:

searchable_like :name

如此一來,就會在搜尋的時候增加如下的sql condition:

["product.name LIKE ?", name]

除了searchable_like, 你還可以用

searchable_equal, 
searchable_less_than, 
searchable_less_and_equal_than, 
searchable_greater_than, 
searchable_greater_and_equal_than

例如

searchable_greater_than :price, created_at
searchable_less_than :order_number

如果你需要針對欄位,進行between的搜尋,你可以:

date_searchable_between :created_at, :begin_of_created_at, :end_of_created_at

如此一來,就會在搜尋的時候增加如下的sql condition:

["product.created_at BETWEEN ? AND ?", begin_of_created_at, end_of_created_at]

第一個參數是column名稱,第二個與第三個參數,則是你希望搜尋的起始日期與結束日期。 between的搜尋,你還可以使用float_searchable_between, integer_searchable_between, 主要的差別就是欄位的資料型態。

Controller

利用這個方式,你的controller會變得非常的精簡

class ProductionsController << ApplicationController
  def index
    @product = Product.new
    @products = @product.search_all
  end
end

View

在view中,搜尋條件的寫法就跟你在new.html.erb 或 edit.html.erb的寫法是非常相似的:

<% form_for(@product, :html => {:url => "/products", :method => 'get'}) do |f|-%>
  <p>
    <label>名稱:</label>
    <%= f.text_field :name -%>
  </p>

  <p>
    <label>建立日期:起</label>
    <%= f.begin_of_created_at -%>
    <label>迄</label>
    <%= f.end_of_created_at -%>
  </p>
<% end -%>

About

search_builder is a rails plugin to generate search form for models easily

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages