I've been making a search page for my service, and it includes several association based search parameters, I can think of a few messy long sql mess, but would prefer some cleaner approaches, as a sample,
class Person < ActiveRecord::Base
has_many :friends
end
Friend has an attribute that indicates the state of the friendship, something like friend_type
class Friend < ActiveRecord::Base
belongs_to :person
end
The search form would consist of many parameters, two of them being searching for people who have more than a certain number of friends, and how many people have friends that have friend_type set to, say "bff".
What I would like to do is have some scope methods in the model, and in the Controller be able to do this,
some model scopes in Person like this,
scope :by_friends_count_greater_than, lambda { |value| joins(:friends).where( #count friends#, value ) if value }
scope :by_bff_count_greater_than, lambda { |value| joins(:friends).where( ##count friends with bff status## , value ) if value }
and call them in the controller as so,
@people = Person.by_friends_count_greater_than(params[:query][:friends_count])
.by_bff_count_greater_than(params[:query][:bff_count])
I have been trying out squeel, which seems to be a very nice asset, considering it can call methods in the query. Is it possible to have search queries done in this fashion?
If there is a better way to approach this, that would be very appreciated.