ActiveRecord - 为每个关联检索一条记录

时间:2012-02-24 03:23:03

标签: ruby-on-rails-3 activerecord

Merchant has_many Shops

Shop belongs_to Merchant

即。一个merchant(星巴克)可以有很多商店。

我正在使用Gecoder来获取附近的商店,例如@shops = Shop.near("Times Square")

我想仅为每个商家返回1条记录。即@shops只包含1个星巴克,1个地铁,但是是一个集合。

抱歉,我一直在谷歌搜索并搜索SO无济于事。也许我没有使用正确的词来描述我想要的东西。提前谢谢。

2 个答案:

答案 0 :(得分:1)

要在scope内回答您应该使用Google搜索,加入或合并查询的内容,可能会解决您的目标。如果您使用:or逻辑组合查询构建范围,每个商店各一个,仅限于第一条记录,您应该得到您想要的内容。

我不会假装我理解Geocoder或高级范围足以做到这一点,但我找到了一个在另一个问题中显示这种方法的例子:

named_scope :or, lambda { |l, r| {
  :conditions => 
      "annotations.id IN (#{l.send(:construct_finder_sql,{:select => :id})}) or " + 
      "annotations.id IN (#{r.send(:construct_finder_sql,{:select => :id})})" 
}}

这来自这个问题:Combine two named scopes with OR (instead of AND)

希望这可以帮助您找到解决方案。

答案 1 :(得分:1)

我用google搜索了一下,偶然发现了group by的SQL。

如果我4 shops belonging to 2 merchants附近有一个名为“莱佛士坊”的地方,请1 kilometer内。

致电Shop.near("Raffles Place",1)会返回4 shops

如果我向group添加Shop.near("Raffles Place",1).group(:merchant_id),则仅返回2 shops

这也可以与其他条件一起使用,例如Shop.where(:featured=>true).group(:merchant_id)仅显示每个特色商家的1个商店。

相关问题