ruby-on-railsrubynamed-scope

Initialize instance variable through named scope


Is it possbile to initialize an instance variable through a named scope? I want to remember my search criteria after the initial search. See the following:

class Foo < ActiveRecord::Base    
  attr_accessor :search

  named_scope :bar, lambda {|search|
    # Do something here to set the @search variable to search
    {
      :conditions => [
        "name LIKE :search OR description LIKE :search", 
        {:search => "%#{search}%"} ]
    } 
  }

  def match
    if name.match(@search)
      :name
    elsif description.match(@search)
      :description
    end
  end
end

Alternatively, I could create a class method that calls the named scope and then iterates through the results to set the instance variable on each, but I lose the named scope chainability in that case.


Solution

  • named scopes are not instantiating any single record, until they are iterated. And they may be, as you correctly say, be chained with more scopes.

    I see two possible solutions. One relies on the database to populate a fake column with the matching value. It should be simple using a special :select option to the query (or a special argument to .select() in rails 3)

    The other is to rely on the controller. This is much easier to implement, but you have to ensure that the "match" in ruby is the same than the "LIKE" in the database. I'm speaking about collation, unicode normalized forms etc. Most probably there is at least one case in which they behave differently in both engines.