Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

searching using active_record scope #235

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jana4u
Copy link

@jana4u jana4u commented Aug 13, 2013

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
Contributor

Thumbs up for this pull request!

@manusajith
Copy link
Member

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

@jana4u
Copy link
Author

jana4u commented Nov 25, 2013

@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
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