ActiveModel Serailizers, how can I load it and why do I need to?

30 views
Skip to first unread message

Chris P.

unread,
Jun 12, 2014, 10:18:49 AM6/12/14
to rubyonra...@googlegroups.com
Noobie here.

The gist of my problem is this. If I move from serializer file from
app/serializers/ to app/models/ then everything works fine. My JSON API
will output my data according to my serializer. However, if I remove the
copy from the app/models/ directory... it no longer works and goes back
to Rails default JSON output.

What do I need to do to include my serializer file in app/serializers/?

**/app/serializers/item_serializer.rb**

class ItemSerializer < ActiveModel::Serializer
attributes :id, :name
end

**/app/controllers/items_controller.rb**


class ItemsController < ApplicationController
respond_to :json

def index
items = Item.all
respond_with ({ success: :true, items: items }.as_json)
end

def show
@item = Item.find_by_id(params[:id])
if @item
render json: @item, serializer: ItemSerializer
else
render json: { success: :false, error: "Could not find
item."}, status: :not_found
end
end
end

Do I HAVE TO have my serializers in /app/models by default. Why would
ActiveModel Serializers default generating a new serializer then to the
/app/serializers directory. How do I let my controller know about my
serializer?

--
Posted via http://www.ruby-forum.com/.

mike2r

unread,
Jun 13, 2014, 10:40:26 AM6/13/14
to rubyonra...@googlegroups.com
I'm not sure exactly what you are trying to do, but with Rails 4, but most of it is unnecessary and is handled automatically unless there's a twist I'm not seeing here.  serialization is now automatic as is responding with an error if the item isn't found.  Unless there's a unique aspect to what you're doing, you don't need your own serializer.  All you should need is the following:

class ItemsController < ApplicationController
   respond_to :json

   def index
      @items = Item.all
      respond_with(@items)
   end

   def show
      @item = Item.find(params[:id])
      respond_with(@item)
   end
end
Reply all
Reply to author
Forward
0 new messages