【发布时间】: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
在处理此查询时,我认为我应该执行以下操作:
-
joinauthor、book、book_store表@authors_books = Author.joins(books: :book_store) -
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") -
groupby 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