Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use current_user in Serializer #4

Open
byhbt opened this issue Jun 25, 2020 · 0 comments
Open

How to use current_user in Serializer #4

byhbt opened this issue Jun 25, 2020 · 0 comments
Labels
Ruby Learning Ruby on Rails
Projects

Comments

@byhbt
Copy link
Owner

byhbt commented Jun 25, 2020

Problem:

class ThirdPartySerializer < ActiveModel::Serializer
  attributes :session_id, :token, :started_at

  def token
    additional_data = {
      role: current_user.role,
      userId: current_user.id
    }.to_json

    THIRD_PARTY.generate_token(object.session_id, data: additional_data)
  end
end

In this context, the current_user is undefined.

Solution:

Add a private get current user to the serializer.

class ThirdPartySerializer < ActiveModel::Serializer
  #....(existing code)

  private

  def current_user_fallback
    @current_user_fallback ||= @instance_options[:current_user] || current_user
  end
end

Lesson:

@byhbt byhbt added the Ruby Learning Ruby on Rails label Jun 25, 2020
@byhbt byhbt added this to To do in Learning Jul 15, 2020
@byhbt byhbt added this to the First 50 issues milestone Jul 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Ruby Learning Ruby on Rails
Projects
Learning
  
To do
Development

No branches or pull requests

1 participant