Forum: Ruby on Rails Abstracting a search feature

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
56f875b595affe29385e07dd32465e4e?d=identicon&s=25 Limbo (Guest)
on 2007-02-01 10:24
Dear Railers,

I'm trying to design a Search controller that will search my social
network website for Friends and Colleagues. However, I would like to
have some kind of encapsulation so that the Friend and Colleagues models
are responsible for performing their own searches, returning the results
to the Search, formatted according to their own separate views.

I think this is the right way to do things because these two different
models would be searching over different columns and returning different
forms of results (Colleagues might have a 'workplace', for example).
Also, this would make the system more extensible in the future, if I
need to add a Classmate object etc.

My question is simply, what's the best way to do this? I am new to Ruby
and Rails, so I am not sure how the classes can interact, how I should
be passing around the search parameters and returning results with
set-specific views. Also I am worried that if both the Friend and
Colleague models are performing the search themselves, this would
violate the DRY principle.

Any help would be much appreciated,

Limbo
56f875b595affe29385e07dd32465e4e?d=identicon&s=25 Limbo (Guest)
on 2007-02-01 20:35
Does anyone have any suggestions at all? :(

Limbo
6d57db44c5a4e0721cc7f78cf0ce308a?d=identicon&s=25 Stephen Bartholomew (steveb)
on 2007-02-01 21:06
(Received via mailing list)
> Does anyone have any suggestions at all? :(
I just found some old code I wrote that adds a basic search method to
active record.   You'll probably want to extend it (add fix bugs!) but
hopefully it'll give you a starting point and show you how you can
approach this problem.

module ActiveRecord
  class Base
    def self.search(keywords)
      keywords = keywords.split(" ")
      sql_conditions = ""

      keywords.each do |word|
        sql_conditions << "("

        columns.each do |column|
          sql_conditions << "#{column.name} LIKE '%#{word}%' OR " if
column.type == :string
        end

        sql_conditions.gsub!(/OR $/, '')
        sql_conditions << ") AND "
      end
      sql_conditions.gsub!(/ AND $/, '')

      find(:all, :conditions => sql_conditions)
    end
  end
end

Stick that in a file called active_record_extensions.rb (or something)
and save it to lib/.  You'll need add a require line to your
environment.rb:
require 'lib/active_record_extensions'

You should then be able to do a basic search like this:
ClassMate.search("stephen bartholomew")

Hope that helps,

Steve
This topic is locked and can not be replied to.