Plugin Development: List a user’s groups without making a request

As per “https://meta.discourse.org/t/getting-users-custom-groups-problems/37792”, the property Discourse.User.current().groups isn’t exposed to all pages.

As per “Discourse docs: Get a single user by username”, the response payload includes a groups array which would be sufficient.

However, I would prefer to not send a request for this information if I can get it without. Is there a way to list a user’s groups without sending a request?

I need to access a user’s group within my plugins Ember route.

2 « J'aime »

You can add custom plugin code to achieve this. Something similar to below code (unverified). Then you can access it like Discourse.User.current().groups

  add_to_serializer(:current_user, :groups, false) {
    object.groups.pluck(:name)
  }
9 « J'aime »

Great, that’s exactly what I was looking for. Logging Discourse.User.current().groups now:

[ "trust_level_0", "trust_level_1", "admins", "staff", "TestGroup" ]
4 « J'aime »

I was discussing with @eviltrout about adding this per default for the current user serializer since many themes can benefit from this.

Is this still in your plans @eviltrout ?

8 « J'aime »

@maja, can you add that to your list?

We should always serialize all the group names of the current user (not only the primary group).

14 « J'aime »

Current user’s groups were added to the serializer:

https://github.com/discourse/discourse/commit/98d09c90acc503051d02094a9f25113eb5fdf293

11 « J'aime »

How does one get a user’s groups in the Rails application? Via current_user, I have access to a user’s username, etc. but I can’t find a way to access their groups.

Did you try current_user.groups? That should work

5 « J'aime »

Yes, that works. Thank you. I did try logging that and it came up as not defined. I suppose I must’ve had a typo.

4 « J'aime »