I am sure this might be a stretch but I'm very impressed with the flexibility that Active Model Serializers provide. I'd like to something like:
def by_location_and_bin_number
@items=MenuItem.where('bin_number=? and location_id=?', params[:bin_number], params[:location_id]).is_valid
r={}
r[:status]="success"
r[:count] = @tems.count
r[:menu_items] = @items, serializer: ItemMicroSerializer # <- not working
render json: r.to_json
end
but this doesn't work. How can I get this to work (or similar syntax)?
As you want to serialize the array @items
, you can use the independent method as
r[:menu_items] = ActiveModel::ArraySerializer.new(@items, each_serializer: ItemMicroSerializer)
It will serialize the provided array of objects by serializing each object using ItemMicroSerializer.