2

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!

jnahum
  • 41
  • 2
  • 6
  • Which version are you using? At least in 0.10 the `current_user` will be defined on the serializer. I believe in previous versions it was accessible through the `scope` method. – beauby Oct 25 '15 at 21:30

2 Answers2

2

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

  • This works! I have been searching for hours!! In my app, I put this in my controller render json: @posts, :user => User.find(params[:user_id]) – miracle-doh Nov 25 '15 at 02:46
  • For others using newer versions of AMS (version 0.10.5 in my case) -- `options` is now `instance_options`. So instead of `options[:my_var]` you would use: `instance_options[:my_var]` – Thomas Apr 13 '17 at 15:07
0

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

Community
  • 1
  • 1
matanco
  • 2,096
  • 1
  • 13
  • 20