0

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.

Saifis
  • 2,197
  • 1
  • 22
  • 36

1 Answers1

0

You might be interested in counter_cache to have simpler queries.

It will auto increment a counter to each Person model.

http://railscasts.com/episodes/23-counter-cache-column

You have to add a friends_count column to your Person model

and specify the counter_cache on the belongs_to

class Friend < ActiveRecord::Base
  belongs_to :person, counter_cache: true
end
yannick
  • 661
  • 4
  • 9
  • That's a way I haven't thought about, thank you for the advice. It would work with the count of normal friends, but it wouldn't work on counting the friends with specific attributes set to them, if I understand counter caching correctly. – Saifis Jul 02 '13 at 23:58
  • Nope but the way counter caches works can be handmade for efficient queries too. If needed – yannick Jul 03 '13 at 06:11