我有许多关联在一起的对象,我想布局一些仪表板来展示它们。为了争论:
我想要一个仪表盘,上面写着:
一家出版社这个月出版了多少本书?一位作家这个月写了多少本书?
首先,我在想一些非常简单的代码:
@all_books = Books.find(:all, :joins => [:author, :publishing_house], :select => "books.*, authors.name, publishing_houses.name", :conditions => ["books.created_at > ?", @date])然后,我继续遍历我想要的每个子元素,并将它们合并到新的数组中,比如:
@ph_stats = {}
@all_books.map {|book| @ph_stats[book.publishing_house_id] = (@ph_stats[book.publishing_house_id] || 0) + 1 }这感觉不太像-想法?
发布于 2010-07-21 20:48:42
我认为你最好的办法是把命名的作用域链在一起,这样你就可以做如下的事情:
@book= Books.published.this_month
http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#M001683 http://m.onkey.org/2010/1/22/active-record-query-interface
发布于 2010-07-21 22:20:01
您应该认真考虑编写这样一个查询所需的SQL,因此,以下查询应该可以在所有数据库中工作:
出版社的图书数量
PublishingHouse.all(:joins => :book, :select => "books.publishing_house_id, publishing_houses.name, count(*) as total", :group => "1,2")作者本月写的书数量
如果你要把它移到一个范围里,你需要把它放在一个λ中。
Author.all(:joins => :books, :select => "books.author_id, author.name, count(*) as total", :group => "1,2", :conditions => ["books.pub_date between ? and ?", Date.today.beginning_of_month, Date.today.end_of_month])这是由于使用了Date.today,或者--您可以使用now()::date (postgres专用的)并在此基础上构造日期。
特定状态的图书
不太确定这是正确的wrt您的数据模型
Book.all(:joins => :state, :select => "states.name, count(*) as total", :group => "1")所有这些都是通过SQL的魔力完成的。
https://stackoverflow.com/questions/3303356
复制相似问题