试图从两级深度关联中找到项目计数,有什么想法吗?
我正在开发一个应用程序,我需要查找用户推荐的用户提交的项目的数量。
例如 -
User1 推荐了 3 个人(User2、User3、User4),每个用户都提交了 5 篇文章。
我正在尝试找到一种方法来获取 User1 树中已提交项目的计数(在这种情况下应该是 15)。
我的用户模型如下所示(简化),
class User < ActiveRecord::Base
# Code for user referrals
belongs_to :referrer, :class_name => "User"
has_many :referrals, :class_name => "User", :foreign_key => "referrer_id"
has_many :items
end
我可以轻松找到每个用户的计数(User.items.size),但我无法找到一种解决方案来将推荐计数作为一个总和。
有什么想法吗?
I am working on an application where I need to find the count of submitted items by users that have been referred by a user.
For Example -
User1 has referred 3 people (User2, User3, User4) and each of those users has submitted 5 articles.
I am trying to find a way to get the count of submitted items in User1's tree (should be 15 in this case).
My user model looks like the following (simplified)
class User < ActiveRecord::Base
# Code for user referrals
belongs_to :referrer, :class_name => "User"
has_many :referrals, :class_name => "User", :foreign_key => "referrer_id"
has_many :items
end
I can find out the count for each user easily (User.items.size), but I am having trouble finding a solution to get the referral counts as one sum.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
您可以使用 select_value 手动运行 SQL 查询:
好处是它比使用 Ruby 计数更具可扩展性。
You can use select_value to manually run the SQL query:
The benefit is that it is a lot more scalable than using Ruby to count.
获取id为1的User的所有项目
Get all items of User with id of 1