【问题标题】:Postgresql error when using Rails' uniq method使用 Rails 的 uniq 方法时出现 Postgresql 错误
【发布时间】:2013-05-03 14:40:19
【问题描述】:

我有一个属于Product 模型的Item 模型。 Product 有一个 hstore 类型的 properties 列。我想返回一组 unique items 属于产品,并且不包括当前项目:@item.similar_items

class Item < ActiveRecord::Base
  belongs_to :product
  scope :by_platform, ->(value) { joins(:product).merge(Product.by_platform(value)) }
  scope :by_genre, ->(value) { joins(:product).merge(Product.by_genre(value)) }

  def similar_items
    Item.includes(:product)
      .by_platform(self.product_platform)
      .by_genre(self.product_genre)
      .limit(3).where.not(product: self.product)
      .order("(properties -> 'release_date')::date DESC")
      .uniq
  end
end

class Product < ActiveRecord::Base
  store_accessor :properties, :platform, :genre
  has_many :items

  scope :by_platform, ->(value) { where("properties @> hstore('platform', ?)", value) }
  scope :by_genre, ->(value) { where("properties @> hstore('genre', ?)", value) }
end

错误:

PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...e')) AND ("items"."product_id" != 426)  ORDER BY (properties...

【问题讨论】:

    标签: ruby-on-rails postgresql uniq hstore


    【解决方案1】:

    如错误消息所述...

    test=> select distinct id from test order by f;
    ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
    LINE 1: select distinct id from test order by f;
    

    将排序列添加到语句的选择部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2014-09-17
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多