ruby on rails - Getting information from the join table in a has many through query -


Imagine 3 models: users, clubs and userclub.

  class user & lt; ActiveRecord :: Base is_Maney: Club, via :: UserColob is_Im: User_Clus & Class Club & lt; ActiveRecord :: Base is has_many: Users, through: user_clubs have_many: user_clubs and class UserClub & lt; ActiveRecord :: Base is_to: related to user: Club End  

Contains very specific table contents.

Now, imagine a situation where you want to retrieve a user's club and the amount of users present in each club.

In one controller, it is easy to regain a user club:

  DIF index @ club = current_user  

Although puzzle I do not know how to do it efficiently.

Of course, I can do something like this:

  DIF index @ club = current_user.club @no_off_users_on_club = hash.new (0) @ club.each up! Club | @no_of_users_per_club [club.id] = UserClub.where (club_id: club.id). Point end # Whatever you will do after the end  

Is there a better way to do this? This will be a child unnecessary, but ultimately, perhaps the best solution is to store the integer as a feature of each network so that when a user joins a club, then I raise it from one and when If a user leaves a club, can I reduce it one by one?

Update: The selected answer below shows a very cool way of doing this and shows a cooler way to limit the results to your clubs.

@noof_user_on_club_of_en = userclub Joins (join user_clouds as "user_club.club_id = uc.club_id") where ("uc.user_id =?", Current_user.id). Group ("user_clubs.club_id"). Count ("user_clubs.user_id")

You group Receive directly from Model Model 'TableClub' to get count in each club in username .

  @no_off_users_close = userclub.group (: club_id). Count (: user_id) # = & gt; {1 = & gt; 1, 2 = & gt; 5, 3 = & gt; 8}  

To get the number of users in each club, where these clubs are joined by the current user:


Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -