How to add user data to the post serializer?

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!

1 Like

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
2 Likes