ruby on rails - How can I count the object with condition? -


community has_many :codes
code belongs_to :community

user has_many :codes
code belongs_to :user

@community.codes.users.count 

this returns number of users code belonging community.

code has column called visible boolean

what if want count number of users code true on visible, belonging community?

is possible count that?

i mean, i'd obtain number of count that's calculated below.
want in 1 line.

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

this line equivalent need. give exact result.

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

there better aproach. should use namedscope such types queries can use multiple times need:

in user model:

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

and can call anywhere

user.visible_in_community(@community.id) 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -