I have two models:
user.rb
attributes: name
, gender
and
participation.rb
attributes: user_id
+ some other
A user has_many :participations
A participation belongs_to :user
I now simply want to find out how many males do I have for a participation collection:
@participations = Participation.all
@males = @participations.joins(:user).where(gender: 'male').count
I understood it this way that I have to join the user model through participations like in the above snippet but that does not work.
Another way would be to simply write:
@males = @participations.users.where(gender: 'male').count
I think I misunderstood something essential here. How can I solve my problem "the rails way"?
您也可以通过:includes
使用预先加载:
@males = @participations.includes(:user).where(users: {gender: 'male'})
您应该在查询中指定表名,如下所示:
@males = @participations.joins(:user).where(users: {gender: 'male'})
我将在用户上定义一个男性作用域,然后在您合并该作用域的参与者上定义一个新的关联“ males”或“ male_users”,以使您能够:
@participations.male_users.count
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.