2013-07-02 39 views
0

我一直在为我的服务制作一个搜索页面,它包含了几个基于关联的搜索参数,我可以想到一些凌乱的长SQL混乱,但是会更喜欢一些清洁方法,作为样本,Rails查询包含关联关系计数,最好使用范围

class Person < ActiveRecord::Base 
    has_many :friends 
end 

朋友具有指示友谊的状态的属性,像friend_type

class Friend < ActiveRecord::Base 
    belongs_to :person 
end 

搜索表单将包括许多参数的东西,他们两个人是寻找比交流更多的人某些朋友,以及有多少人拥有friend_type设置为“bff”的朋友。

我想什么做的是在模型的一些范围的方法,并在控制器能够做到这一点,

的人一些像这样的模型范围,

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 } 

和呼叫他们在控制器等等,

@people = Person.by_friends_count_greater_than(params[:query][:friends_count]) 
       .by_bff_count_greater_than(params[:query][:bff_count]) 

我一直在尝试squeel,这似乎是一个很不错的资产,认为它可以调用查询方法。是否有可能以这种方式完成搜索查询?

如果有更好的方法来解决这个问题,那将非常感激。

回答

0

您可能对counter_cache感兴趣,以获得更简单的查询。

它会自动增加计数器到每个人模型。

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

你有一个FRIENDS_COUNT列添加到您的Person模型

,并在belongs_to的

class Friend < ActiveRecord::Base 
    belongs_to :person, counter_cache: true 
end 
+0

这是我没有想过的方式指定counter_cache,谢谢你建议。它可以处理普通朋友的计数,但如果我正确理解计数器缓存,则无法计算具有为其设置的特定属性的朋友。 – Saifis

+0

不,但计数器缓存工作的方式也可以手工制作以进行高效查询。如果需要的话 – yannick