Skip to content

searching using active_record scope#235

Open
jana4u wants to merge 1 commit into
crowdint:masterfrom
jana4u:search_scope
Open

searching using active_record scope#235
jana4u wants to merge 1 commit into
crowdint:masterfrom
jana4u:search_scope

Conversation

@jana4u

@jana4u jana4u commented Aug 13, 2013

Copy link
Copy Markdown

Added ability to use active record scope for search. It enables using complex queries (use OR, JOIN other tables etc.) in search.

Example usage:

In model just add scope with lamba and one parameter. In this example it is called :autocomplete_by_names:

class User < ActiveRecord::Base
  scope :autocomplete_by_names, lambda { |query|
    select("users.contact_name, users.business_name").where("(users.contact_name LIKE :query OR users.business_name LIKE :query)", :query => query)
  }

  def name_with_id
    "#{business_name.blank? ? contact_name : business_name} (#{id})"
  end
end

In controller in autocomplete call use just :id (if you don't want any other column to be selected from database or if you use select in your scope) and add new option :search_scope and specify the name of your scope :autocomplete_by_names:

class UsersController < ApplicationController
  autocomplete :user, :id, :full => true, :display_value => :name_with_id, :search_scope => :autocomplete_by_names
end

All other autocomplete options work with this.

@marzapower

Copy link
Copy Markdown
Contributor

Thumbs up for this pull request!

@manusajith

Copy link
Copy Markdown
Member

@jana4u I think there is already an option to pass scopes, Details here

@jana4u

jana4u commented Nov 25, 2013

Copy link
Copy Markdown
Author

@manusajith Yes, but you can use only scopes without parameters - for example:

scope :admin, where(:admin => true)

There is no way to pass search query to those scopes. You can restrict or reorder results using current :scopes option, but you can't change the way how results are found.

@manusajith

Copy link
Copy Markdown
Member

@jana4u got it. There are a few other PR too addressing the issue to pass parameters to the scope.
Will check all and will merge the best one.
Thanks for your PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants