【问题标题】:Activerecord query: sort model by average of association's modelActiverecord 查询:按关联模型的平均值对模型进行排序
【发布时间】:2021-04-03 05:59:20
【问题描述】:

我有一个模型 Place,它有评论,其中有一列星星。

我尝试了以下查询:

Place.select('place_id, name, avg(reviews.stars)').join(:reviews).group('place_id, name').order('avg(reviews.stars) desc')

我收到以下错误:

PG::UndefinedColumn: 错误:列“place_id”不存在第 1 行:从“places”中选择 place_id、名称、avg(reviews.stars) ^ : 选择 place_id、name、avg(reviews.stars) FROM “地方”

他怎么能抱怨place_id?此列由 Rails 创建。我该如何解决这个问题?

我的模型是:

class Review < ApplicationRecord
  belongs_to :place
end

class Place < ApplicationRecord
  has_many :reviews
end

架构如下:

  create_table "reviews", force: :cascade do |t|
    t.integer "stars"
    t.string "content"
    t.bigint "place_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["place_id"], name: "index_reviews_on_place_id"
  end

  create_table "places", force: :cascade do |t|
    t.bigint "user_id"
    t.string "name"
    t.string "description"
    t.float "lng"
    t.float "lat"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.float "latitude"
    t.float "longitude"
    t.string "address"
    t.index ["user_id"], name: "index_places_on_user_id"
  end

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    join 是一种委托给基础记录的方法,导致在您的select 之后直接调用Array#join

    您想调用joins 而不是join 来构造正确的查询。如果您仔细查看您的错误,您会发现select 之后的所有内容都已被忽略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 2020-09-10
      • 1970-01-01
      • 2018-03-25
      相关资源
      最近更新 更多