search_scope

Rails gem for simplify searching a model by defining custom named_scopes.

Install

gem install search_scope

Usage

…coming soon

Tutorial

#this tutorial will show you how to create a rails app and search using search_scope

#create your new app rails search_scope_test cd search_scope_test

#add models ./script/generate model post title:string author_id:integer body:text ./script/generate model author name:string code:string rake db:migrate

#add to environment.rb (below the other config.gem examples) config.gem ‘search_scope’, :version => ‘>= 0.1.4’

#install the gem (from the command line) rake gems:install

#edit the models class Author < ActiveRecord::Base

has_many :posts

sort_search_by :name
search_scope :name
search_scope :code, :search_type => :exact_match

end

class Post < ActiveRecord::Base

belongs_to :author

sort_search_by  :title
sort_search_by  :author_name,  :label => 'Author', :order => "authors.name, title", :include => :author

search_scope :title
search_scope :body
search_scope :author_name,  lambda { |term| { :conditions => ["authors.name LIKE ?", "%#{term}%"], :include => :author } }

def description
  "\"#{title}\" by #{author.name}"
end

end

#add some data (from the command line) ./script/console

joe = Author.create :name => ‘Joe Schmo’, :code => ‘joe’ jack = Author.create :name => ‘Jack Sprat’, :code => ‘jack’

Post.create :title => ‘Hello World!!’, :body => ‘Just saying hi.’, :author_id => joe.id Post.create :title => ‘I am NOT Jack!’, :body => ‘The OTHER guy is Jack, not me.’, :author_id => joe.id Post.create :title => ‘My last name is Schmo, not Blow.’, :body => ‘Seriously, get it right people.’, :author_id => joe.id Post.create :title => ‘It's cold out.’, :body => ‘Can't wait for summer.’, :author_id => joe.id

Post.create :title => ‘Hello World!!’, :body => ‘Just saying hi.’, :author_id => jack.id Post.create :title => ‘I'm in the dog house.’, :body => ‘I bought my wife a gym membership for Christmas. oops.’, :author_id => jack.id Post.create :title => ‘Steak is delicious.’, :body => ‘No, seriously, it is. Even Joe likes it.’, :author_id => jack.id

#do some searching (from script/console) Author.count #=> 2 Post.count #=> 7

Author.search(:name => ‘joe’).size # => 1 Author.search(:name => ‘j’).size # => 2 Author.search(:code => ‘j’).size # => 0 Author.search(:code => ‘joe’).size # => 1

puts Post.search(:title => ‘cold out’).collect(&:description).join(“n”) # => “It’s cold out.” by Joe Schmo

Post.search(:title => ‘hello’).size # => 2 Post.search(:title => ‘hello’, :author_name => ‘joe’).size # => 1

#sorting puts Post.search(:title => ‘a’, :sort_by => :title).collect(&:description).join(“n”) puts Post.search(:title => ‘a’, :sort_by => :author_name).collect(&:description).join(“n”)

#quick_search puts Post.search(:quick_search => ‘jack’, :sort_by => :title).collect(&:description).join(“n”) puts Post.search(:quick_search => ‘jack’, :sort_by => :author_name).collect(&:description).join(“n”)