想象一下3种型号:用户,俱乐部和用户俱乐部。
class User < ActiveRecord::Base
has_many :clubs,
through: :user_clubs
has_many :user_clubs
end
class Club < ActiveRecord::Base
has_many :users,
through: :user_clubs
has_many :user_clubs
end
class UserClub < ActiveRecord::Base
belongs_to :user
belongs_to :club
end
非常典型的联接表格。
现在,假设您想要检索一个用户俱乐部和每个俱乐部中的用户数量。
在控制器中,检索用户俱乐部很简单:
def index
@clubs = current_user.clubs
#do whatever you will with them
end
第二部分让我感到困惑,因为我不知道如何尽可能有效地做到这一点。
当然,我可以这样做:
def index
@clubs = current_user.clubs
@no_of_users_per_club = Hash.new(0)
@clubs.each do |club|
@no_of_users_per_club[club.id] = UserClub.where(club_id: club.id).count
end
#Do whatever you would do after
end
有更好的方法吗?这可能是多余的,但最终,也许最好的解决方案是简单地将该整数存储为每个网络的属性,这样当用户加入俱乐部时,我将其增加一,当用户离开俱乐部时,我把它减少一个?
更新:下面选择的答案显示了一种非常酷的方式,以及将结果限制在俱乐部的更酷的方法。
@no_of_user_per_club_of_mine = UserClub.
joins("INNER JOIN user_clubs AS uc ON user_clubs.club_id = uc.club_id").
where("uc.user_id = ?" , current_user.id).
group("user_clubs.club_id").
count("user_clubs.user_id")
答案 0 :(得分:4)
group
直接从加入模型&#39; TableClub&#39; count
中的users
club
。{/ h3>
@no_of_users_per_club = UserClub.group(:club_id).count(:user_id)
# => {1=>1, 2=>5, 3=>8}
@no_of_user_per_club_of_mine = UserClub.joins("INNER JOIN user_clubs AS uc ON user_clubs.club_id = uc.club_id").where("uc.user_id = ?" , current_user.id).group("user_clubs.club_id").count("user_clubs.user_id")
答案 1 :(得分:0)
@count = current_user.user_clubs.group_by{|o|o.club_id}.map{|k,v|[k, v.first.club.users.length]}
This will return a array of array which contain club_id at first index and count of users related to this club at second index
@count.length will return total clubs related to current user