我一直在为我的服务制作一个搜索页面,它包括几个基于关联的搜索参数,我可以想到一些凌乱的长 sql 混乱,但更喜欢一些更干净的方法,作为示例,
class Person < ActiveRecord::Base
has_many :friends
end
Friend 有一个表示友谊状态的属性,例如friend_type
class Friend < ActiveRecord::Base
belongs_to :person
end
搜索表单将包含许多参数,其中两个用于搜索拥有超过一定数量朋友的人,以及有多少人的朋友的朋友类型设置为“bff”。
我想做的是在模型中有一些范围方法,并且在控制器中能够做到这一点,
像这样的 Person 中的一些模型范围,
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,这似乎是一个非常好的资产,考虑到它可以调用查询中的方法。是否可以以这种方式完成搜索查询?
如果有更好的方法来解决这个问题,那将不胜感激。