方法返回一个Array对象

时间:2016-05-21 11:26:46

标签: ruby-on-rails postgresql

我的数据库是PostgreSQL。我正在使用以下代码来消除表中的重复行:

uniqBk = Bikehistory.all(
    :select => 'DISTINCT ON (bikehistories.bike_numbers) *',
    :order => 'bikehistories.bike_numbers'
)

不幸的是,返回的对象是Array而不是ActiveRecord::Relation::ActiveRecord_Relation_Bikehistory

如何获取ActiveRecord对象并获得相同的查询结果?

3 个答案:

答案 0 :(得分:0)

您可以尝试此查询:

Bikehistory.all.includes(:bikehistories).where('DISTINCT ON (bikehistories.bike_numbers) *').order('bikehistories.bike_numbers')

答案 1 :(得分:0)

请尝试使用此查询:

uniqBk = Bikehistory.where("JOIN ( SELECT id, DISTINCT bike_numbers
                                   FROM bikehistories
                                 ) as temp
                            ON temp.id = id")
                    .order(:bike_numbers)

答案 2 :(得分:0)

好吧,对我来说,我更喜欢使用嵌入式查询,如下所示:

class Bikehistory
   scope :unique, -> do
      hists = self.arel_table
      hists.where(hists[:id].in(self.distinct.pluck(:id).to_sql)).order(:bike_numbers)
   end
end

但是Rails也可以处理更简单的解决方案(试一试):

class Bikehistory
   scope :unique, -> { where(id: self.distinct.pluck(:id)).order(:bike_numbers) }
end