3

I have a simple model:

class Receipt
  include ActiveModel::Serialization
  attr_accessor :products
end

and my controller is doing:

def create
  respond_with receipt, :serializer => ReceiptSerializer
end

and the serializer:

class ReceiptSerializer < ActiveModel::Serializer
  attributes :products
end

and I get:

 NoMethodError:
   undefined method `to_model' for #<Receipt:0x007f99bcb3b6d8>

Yet if I change my controller to:

def create
  json = ReceiptSerializer.new(receipt)
  render :json => json
end

Then everything works fine... what is happening???

I was using active_model_serializers 0.9.3, but just tried 0.10.2, and the results are the same.

patrick
  • 9,290
  • 13
  • 61
  • 112

2 Answers2

3

In all the documentation I've read and personal implementation I use render json: instead of respond_with.

render json: receipt, serializer: ReceiptSerializer

I believe that respond_with has been removed from rails and isn't considered a best practice anymore but I can't find a link to validate that claim.

Tyler Ferraro
  • 3,753
  • 1
  • 21
  • 28
  • oh, I thought respond_with was the proper way to use ActiveModelSerializers? did that change? – patrick Jul 24 '16 at 00:43
  • I've never used it that way in the 6 years of using Rails. But that doesn't mean it wasn't at one time the proper way to do it. https://github.com/rails-api/active_model_serializers/blob/master/docs/general/rendering.md – Tyler Ferraro Jul 24 '16 at 00:47
  • 1
    respond_with moved to a gem: https://stackoverflow.com/questions/25998437/why-is-respond-with-being-removed-from-rails-4-2-into-its-own-gem – Simon Woodside Jun 02 '17 at 03:25
0

I'm not totally sure, but it seems in your Receipt PORO, you should rather include: ActiveModel::SerializerSupport.

I can't confirm if that works for active_model_serializers 0.10.2 though

oreoluwa
  • 5,553
  • 2
  • 20
  • 27