How to add user data to the post serializer?

סיכום מבוסס בינה מלאכותית

Adding User Data to Post Serializer

bennett is trying to include the website field from the user profile in the post serializer for a theme or plugin. They were able to update the post serializer with simple data, but struggled to add data from the User object without triggering a database hit for each user/post.

After investigation, bennett found a solution by adding a user_extra_fields field to the post serializer, which contains all user.custom_fields. They used the following code in their theme component:

after_initialize do
  add_to_serializer(:post, :user_extra_fields, false) {
    return object.user.custom_fields
  }
end

This allows them to access user custom fields in their theme components, although the field names are prefixed with user_field_. They were unable to add a field called user_custom_fields, which may be reserved.

I’m trying to create a theme or plugin that will let me add and update links in the post widget. I think the easiest approach would be to include the website field from the user profile in the post serializer, but I can’t quite get it to work.

I have figured out how to update the post serializer to add simple data, but I can’t figure out how to add data that comes from User object that created the post. I’m also concerned about doing it in a way that triggers a database hit for each user/post.

Are there any existing plugins I should look at for guidance? Or even better, is there a way to add post user data to the post serializer by overriding widgets in a theme component without resorting to a plugin?

Thank you!

I think I have this working, at least to a passable degree. I was unable to figure out how to add the website field to the post serializer, and it seems that I can’t add a field called user_custom_fields (perhaps that is reserved). I was able to add a user_extra_fields field that contains all of the user.custom_fields. Then in my theme components I can access those fields as needed (although it’s a bit odd to have to use a field called user_field_1).

The following did what I needed:

after_initialize do
  add_to_serializer(:post, :user_extra_fields, false) {
    return object.user.custom_fields
  }
end