0

社区has_many :codes
代码 belongs_to :community

用户has_many :codes
Code belongs_to :user

@community.codes.users.count

这将返回其代码属于社区的用户数。

代码有名为的列visible布尔值的列

如果我只想计算代码为 true on 的用户数visible,那是属于社区的用户数怎么办?

可以这样算吗?

我的意思是,我想获得像下面这样计算的计数。
我想要它在一行中。

@community.codes.each do |code|
    if code.visible && code.user
        count = count + 1
    end
end
4

3 回答 3

2

This line is equivalent to what you need. It will give the exact result.

User.joins(:codes => :community).where("codes.visible=? AND communities.id=?", true, @community.id).count

There is also another better aproach. You should use namedscope for such types queries so that you can use it multiple times where you need:

In User model:

scope :visible_in_community, (lambda do |community_id|
  joins(:codes => :community).where("codes.visible=? AND communities.id=?", true, community_id) 
end)

And you can call anywhere

User.visible_in_community(@community.id)
于 2013-04-18T17:26:38.590 回答
2

希望这对你有用。

@community.codes.where('visible = ? AND user_id IS NOT NULL', true).count
于 2013-04-18T16:56:46.423 回答
1

以下行等效于您问题的最后一段代码,但效率更高,因为在单个 SQL 请求中:使用 a 获取可见的计数Code并且User属于@community

Code.where('visible = ? AND community_id = ? AND user_id IS NOT NULL', true, @community.id).count
于 2013-04-18T16:57:02.473 回答