2015-10-05 44 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