Search code examples
ruby-on-railsruby-on-rails-3decoratorcode-organizationsunspot

Sunspot: where to put my Model.search code?


I defined my User model as searchable:

class User < ActiveRecord:Base
    searchable do
        #...
    end
end

Now, I'm wondering what's the best place to actually have the search call:

User.search do
    keywords kw
    # insert a toooon of with, facets etc...
end

I don't want to have this huge block in the controller. I'm using draper (implement the decorator pattern), but it's really coupled to a model, so I don't think it's the best place. Or is it?

Should I just create a Search class and do something like

@search = Search::UserSearch(params)

in the controller?

Thanks!


Solution

  • I'd encourage you to put this in Search::UserSearch class. It always a good idea to separate concerns and follow single responsibility principle.

    You can put this class in

    app/models/search/user_search.rb

    (don't forget to add search dir to autoload paths)

    Nevertheless I'm doing this in one of my project and I'm happy with it.