Adding to user serializer does not work for the current user object

I have added custom field in user model but when I tried to fetch in current user object I did not get the custom field. how can I fetch the custom field?

I tried below code

require_dependency 'user_serializer'
class ::UserSerializer
attributes :custom_thumbnail_style_dropdown
def custom_thumbnail_style_dropdown
    object.custom_fields[custom_thumbnail_style_dropdown]
end
end

even I tried object.custom_thumbnail_style_dropdown in the defination but it didnt’ work.

Also tried below code

add_to_serializer(:user, :custom_thumbnail_style_dropdown, false) do
object.custom_thumbnail_style_dropdown
end

Any help would be appreciated!

Hi @Harshit_Dave

Then you should add to CurrentUserSerializer instead of UserSerializer :wink:

For example:

  add_to_serializer(:current_user, :can_create_poll) do
    scope.user&.staff? || scope.user&.in_any_groups?(SiteSetting.poll_create_allowed_groups_map)
  end
2 Likes

Hi @Lhc_fl

Thanks for messaging!

I tried using :current_user serializer but then I got NoMethodError error

I tried below code. I am not sure about code as I am new to discourse:

add_to_serializer(:current_user, :custom_thumbnail_style_dropdown) do
object.custom_thumbnail_style_dropdown
end

Here object is a instance of User, not a UserSerializer. Therefore, you should write something like this:

add_to_serializer(:current_user, :custom_thumbnail_style_dropdown) do
    object.custom_fields["custom_thumbnail_style_dropdown"]
end
4 Likes

It worked for me. Thank you so much!

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.