Ruby on rails Activerecord查询:按关联模型的平均值排序模型

Ruby on rails Activerecord查询:按关联模型的平均值排序模型,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一个有评论的样板间,有一个明星专栏 我尝试了以下查询: Place.select('place_id, name, avg(reviews.stars)').join(:reviews).group('place_id, name').order('avg(reviews.stars) desc') 我得到了以下错误: PG::UndefinedColumn:错误:列place\u id不存在第1行:选择place\u id、name、avgreview.stars FROM places

我有一个有评论的样板间,有一个明星专栏

我尝试了以下查询:

Place.select('place_id, name, avg(reviews.stars)').join(:reviews).group('place_id, name').order('avg(reviews.stars) desc')
我得到了以下错误:

PG::UndefinedColumn:错误:列place\u id不存在第1行:选择place\u id、name、avgreview.stars FROM places^:选择place\u id、name、avgreview.stars FROM places

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

我的模型是:

class Review < ApplicationRecord
  belongs_to :place
end

join是一种委托给基础记录的方法,导致在选择后直接调用

您希望调用联接而不是联接来构造适当的查询。如果仔细查看错误,您会发现select之后的所有内容都已被忽略

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