0
所以我有一個3種型號:作爲模型數組的複合導軌計數查詢?
# Rails table
class Library < ActiveRecord::Base
has_many :books
end
# Rails table
class Book < ActiveRecord::Base
belongs_to :library
end
# Global table used by lots of different apps in different languages
class Stat < ActiveRecord::Base
# No direct relationship because it holds many "stats" for many
# records and not a table created using rails (.NET, Rails,
# and Java project use same Stats table)
end
我有一個查詢,看起來像(度日檢出數量排序的前5名庫):
# Get all books in libraries in San Antonio
# This is actually in a method because it is called by several
# Different actions. It's placed here for reference
books = Book.joins(:libraries).where(libraries: { city_id: 4311 })
# Get number of total checkouts of books in all libraries
books.joins("INNER JOIN `stats` ON `stats`.`statsrecord_id` =
`books`.`statsrecord_id` AND `stats`.`type` = 2").where(statsrecord_id:
books.map(&:statsrecord_id).uniq).group('library_id', 'library_name',
'address_1', 'address_2', 'city', 'state',
'postal_code').page(1).limit(5).order('count_all DESC').count
查詢似乎是工作大。然而,我有三個問題:
首先,有沒有辦法清理它,仍然產生相同的輸出(或是這樣)?
其次,返回的記錄是這樣的:
{[16, "Sounds Library SW", "9133 Culebra Rd", "Building 1055", "San Antonio", "TX", "78251"]=>175}
...
有沒有辦法在型號計數得到這容易嗎?
最後,如果返回值列在上面。我似乎無法弄清楚如何從返回值中提取數據?
任何幫助,將不勝感激!
謝謝。