On Thursday, June 12, 2014 10:18:49 AM UTC-4, Ruby-Forum.com User wrote:
>
> 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/.
>
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
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/77d3ee23-33f8-4f10-aed1-b1526c3efb1f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.