HABTM协会的Rails:收集和统计模型的孩子的类别 [英] HABTM associations in Rails : collecting and counting the categories of a model's children

查看:122
本文介绍了HABTM协会的Rails:收集和统计模型的孩子的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 has_​​and_belongs_to_many 相关设置。它看起来是这样的:

I have a has_and_belongs_to_many relationship setup. It looks like this:

  • have_and_belong_to_many 类别
  • have_and_belongs_to_many 图书
  • 商店的has_many 图书
  • 一书 belongs_to的商店
  • books have_and_belong_to_many categories
  • categories have_and_belongs_to_many books
  • a store has_many books
  • a book belongs_to a store

我试图表现出很多书在每家商店如何属于每个类别。所以,我认为会显示存储X有200本书和80都是谜,60都是非小说等。

I'm trying to show how many books in each store belong to each category. So my view would show Store X has 200 books and 80 of them are mystery, 60 are non fiction, etc.

我一直在尝试了一堆这样的方式不同,但没有成功为止。我想,我开始在错误的地方。任何方向将是非常美联社preciated。

I have been trying out a bunch of different ways of doing this, but no success so far. I think I'm starting in the wrong place. Any direction would be much appreciated.

感谢

这是Rails的4和psql的方式。

This is Rails 4 and psql by the way.

推荐答案

前提是你有一个 books_categories 连接表,你可以添加一个的has_many:类别,通过:书籍关联到哪个环节存储类别图书

Provided that you have a books_categories join table you can add a has_many :categories, through: :books association to which links stores and categories through books.

class Store < ActiveRecord::Base
  has_many :books
  has_many :categories, through: :books
end

这是比较容易的部分。现在,让我们得到每个类别的书籍计数(修订):

That's the easy part. Now lets get each category and the books count (revised):

def books_per_category
  categories.select('categories.id, categories.name, count(books.id) as count').group('categories.id, categories.name').map do |c|
    {
      name: c.name,
      count: c.count
    }
  end
end

礼貌的<一个href="http://stackoverflow.com/questions/30133478/rails-get-count-of-association-through-join-table/30133892?noredirect=1#comment48379098_30133892">@jakub-kosiński

Courtesy of @jakub-kosiński

这篇关于HABTM协会的Rails:收集和统计模型的孩子的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆