Finding all groups of the poster in a topic

AI-generated summary

In a Discourse development discussion titled Finding all groups of the poster in a topic, Lumi seeks to display user group flairs under each post in a topic. While they’ve implemented basic functionality, they’re unable to access user group data via the post-meta-data widget’s attrs. Arkshine suggests extending the post serializer in a plugin to include either :groups or a filtered :available_flairs field containing only flair-relevant group data (name, URL, colors), cautioning that group visibility may not respect permissions. Heliosurge references a related topic on CSS classes for user groups. Lumi confirms the available_flairs approach is ideal but struggles to get it working, suspecting the code should be placed in plugins.rb. Arkshine clarifies that to expose the field in the post-meta-data context, the JavaScript API must be used: api.includePostAttributes("available_flairs"). Lumi confirms this resolved the issue and thanks Arkshine for the help.

I would like to show small flair for all groups of a user on every post in a topic (under the username). I have the basic functionality working, but I hit the wall on finding the groups of the user that made the post. In the attrs of the post-meta-data widget, I can find some details of the user, but groups are not included. I think I need to add the groups to the post serializer, but I’m not sure how to do that.

Hi,

Not an expert – In a plugin, you can add the groups field to the post serializer, something like that:

add_to_serializer(
    :post,
    :groups
) { object.user&.groups }

However, keep in mind that, as it is, anyone can see what group a person is in.
That said, I believe that as long as you’re using a flair, the group’s name will be visible to anyone, regardless of the permissions.

You could also insert a new available_flairs field to return only the group’s flairs necessary fields:

add_to_serializer(:post, :available_flairs) do
  flairs = Array(object.user&.groups&.map do |group|
    next unless group.flair_url
    {
      id: group.id,
      name: group.name,
      url: group.flair_url,
      bgColor: group.flair_bg_color,
      color: group.flair_color
    }
  end).compact

  flairs
end

I hope that helps. :+1:

This component maybe of interest during post creation maybe to add flairs to post during creation?

The second solution is exactly what I’m looking for, but I can’t get it to work. For some reason the available_flairs array doesn’t show up at all. Am I right assuming the code should go to the plugins.rb?

To appear in the post-meta-data context, try using the API. This should work!

api.includePostAttributes("available_flairs");

That did the trick. Thank you for the help!