2015-10-05 50 views
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} 
... 

有沒有辦法在型號計數得到這容易嗎?

最後,如果返回值列在上面。我似乎無法弄清楚如何從返回值中提取數據?

任何幫助,將不勝感激!

謝謝。

回答

0

您可以通過編寫它不使用那些回簡化查詢蜱(「`」):

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 

你返回的對象僅僅是一個哈希說它的名字是data_hash。然後你可以做所有這些事情來提取數據所需的部分(鍵,值等):

data_hash = {[16, "Sounds Library SW", "9133 Culebra Rd", "Building 1055", "San Antonio", "TX", "78251"]=>175} 
# inspect the data_hash 
puts data_hash.inspect 
# get all the keys of data_hash 
puts data_hash.keys.inspect 
# get all the values of data_hash 
puts data_hash.values.inspect