Rails-如何自动uniq联接方法



这个问题是基于这个:Rails,为什么联接返回具有非uniq值的数组?

假设我用.joins()方法得到非uniq数组:

City.joins(:locations)
# => [#<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">, #<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">, #<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">, #<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">]

我可以使用进行uniq记录

City.joins(:locations).group('cities.id') # or simpler
City.joins(:locations).uniq
# => [#<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">]

如何使.joins()方法默认返回uniq记录?

您可以尝试为所需的模型重写.joins方法,但我建议只编写一个范围,例如

scope :unique_locations, -> { joins(:locations).uniq }

然后打电话给City.unique_locations。这样它更干净,可读性更强。

一般来说,只有当你确信不需要"老方法"时,才应该重写方法,而且这是有意义的。另外,当你说City.joins(:locations)时,读者期望默认行为,而返回其他内容会导致混乱和混乱。

您可以定义has_many宏,并将stubby lambda作为参数:

has_many :locations, -> { joins(:locations).uniq }

您也可以定义自己的AR关系方法,它仍然使用一个简单的has_many宏。

has_many :locations do
  def only_uniq     
    joins(:locations).uniq
  end
end

现在使用它:

c = City.find(123)
c.locations.only_uniq

它与CCD_ 11中的CCD_ 9或CCD_。

最新更新