jnahum
jnahum

Reputation: 41

active model serializer with parameter?

I'm using Active Model Serializer and I need to include a parameter that is within the scope of the controller. For example, I'm serializing over posts, but there is a condition between the current_user (variable in PostController) and posts in the Serializer.

class PostSerializer < ActiveModel::Serializer
attributes :id, :active, :favorite

def favorite
  if current_user.favorites.find(object.id) != nil
    return true
  end
end

however, the current_user is undefined. Is there anyway I can send the current_user as a parameter into the Serializer?

thanks a ton!

Upvotes: 2

Views: 3004

Answers (2)

Garden Gnome
Garden Gnome

Reputation: 88

What version of Active Model Serializers are you using? I'm using 0.8.3 anyway it has an options param so you could call the serializer like

PostSerializer.new(post, :current_user => current_user)

and access the current_user option like

def favorite
  if options[:current_user].favorites.find(object.id) != nil
    return true
  end
end

However I suspect it would be cleaner to actually serialize a user which happens to have a relationship to favourite posts

Upvotes: 2

matanco
matanco

Reputation: 2129

i think that this will be the best:

def favorite(user)
  if user.favorites.find(object.id) != nil
    return true
  end
end

just pass the user into the method, because devise current_user use session which not readable straight forward from your model.

other option is read this post:

Access current_user in model

Upvotes: 0

Related Questions