Closed
Description
(from #552) I just realized that AMS is in flux. But I'd throw in my issue (based on 0.9), anyway.
We have a master-detail view where the master shows a list of conversations with the last message included, and the detail displays one conversation with all messages.
One way to do it is:
class Conversation
has_many :messages
has_one :last_message
attr_accessor :show_details
end
class ConversationSerializer < ActiveModel::Serializer
attributes :last_message, :messages
def attributes
if object.show_details
super.except(:last_message)
else
super.except(:messages)
end
end
end
# controller
@conversation.show_details = true
render json: @conversation
But this feels wrong on two fronts:
- The model shouldn't contain view (or serializer, in this case) concerns like
show_details
. There should be a way to directly pass the hint from controller to serializer, not through model. - It doesn't work when it's called from an array context - you need to do
conversations.each{|i| i.show_details = true }
. The hint should be stored at the array level, not at the item level.
For those reason, I would suggest that we enable to pass arbitrary parameters to the serializer, from controller.
class ConversationSerializer < ActiveModel::Serializer
params :show_details
def attributes
if @show_details
super.except(:last_message)
else
super.except(:messages)
end
end
end
# controller
render json: @conversation, serializer_params: { show_details: true }
and pass down the params to each item, when the target was an array.
That way, we don't have to alter the model and separation can be done nicely. What do you think?