【问题标题】:Rails using group and order to query associated tablesRails 使用 group 和 order 查询关联表
【发布时间】:2015-07-12 21:11:15
【问题描述】:

我正在尝试获取那些最昂贵的书位于书店的author 记录:bookworm

以下是我的联想:

#app/models/author.rb
class Author < ActiveRecord::Base
  has_many :books
end

#app/models/book.rb
class Book < ActiveRecord::Base
  belongs_to :author
  belongs_to :book_store
end

#app/models/book_store.rb
class BookStore < ActiveRecord::Base
  has_many :books
end

以及显示表列的部分数据库架构:

#db/schema.rb 
create_table "authors", force: :cascade do |t|
  t.string   "name"
end

create_table "book_stores", force: :cascade do |t|
  t.string   "store_name"
end

create_table "books", force: :cascade do |t|
  t.string   "title"
  t.integer  "cost"
  t.integer  "author_id"
  t.integer  "book_store_id"
end

在处理此查询时,我认为我应该执行以下操作:

  1. joinauthorbookbook_store

    @authors_books = Author.joins(books: :book_store)
    
  2. orderauthor_id, cost

    #first should order by author_id. Then, for author_id ties: it orders by cost in descending order
    @authors_books = @authors_books.order("author_id ASC, cost DESC")
    
  3. group by author_id,检查该作者的第一条记录。如果是book_store.store_name == 'bookworm',则返回。

    #struggling with this part for sure:
    @authors_books = @authors_books.group(:author_id).having("min(book_store.name) like 'bookworm'")
    

之后,@authors_books 应该是 uniq 作者记录的列表,其中最昂贵的书位于书店:bookworm

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord


    【解决方案1】:

    这是解决此问题的一种方法。首先,在 Book 模型上创建一个类方法,以按作者获取最昂贵的书籍:

    # Book model
    def self.max_by_author
      max_costs = group(:author_id).select("author_id, MAX(cost) AS max_cost")
      joins("INNER JOIN (#{max_costs.to_sql}) max_costs ON books.author_id = max_costs.author_id AND books.cost = max_costs.max_cost")
    end
    

    然后您可以使用 merge 将其与 BookStore 和 Author 查询结合起来以获得您需要的内容。要查找在“书虫”出售的最大书籍,您可以使用:

    Book.max_by_author.joins(:book_store).merge(BookStore.where(store_name: "bookworm"))
    

    要查找在“书虫”出售的最大书籍的作者,您可以使用:

    Author.joins(:books).merge(Book.max_by_author.joins(:book_store).merge(BookStore.where(store_name: "bookworm"))).uniq
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 2021-03-30
      • 2019-09-12
      • 2013-02-09
      相关资源
      最近更新 更多