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

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?

On Thursday, June 12, 2014 10:18:49 AM UTC-4, Ruby-Forum.com User wrote:

  respond_to :json
    else


Posted via http://www.ruby-forum.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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs