I want to send a json
response containing a collection of my bookmarks
resource. For some reason active model serializer is just not manipulating my json as expected. It's only rendering the default response.
Here is my BookmarksSerializer
serializer in app/serializers/bookmarks_serializer.rb
class BookmarksSerializer < ActiveModel::Serializer
attributes :id, :url, :title
end
and my controller method inside my Api::UsersController
which has a respond_to :json
filter on top
def index
user = User.find_by(username: params[:username])
@bookmarks = user.bookmarks
render json: @bookmarks.to_json
end
Instead of getting only :id, :title and :url, I am getting the full default hash
What am I doing wrong? I am using rails 4.1.5
and the github version of the active_model_serializers
gem.
gem 'active_model_serializers', github: 'rails-api/active_model_serializers'
FYI: I have a show method inside the same controller and it's serializer picks up the single resource just fine. It's just the collection in the index method that is not rendering. Please help
Try this
render :json => @bookmarks, each_serializer: BookmarksSerializer
You are using the master branch of active model serializers. The array serializer was added 4 days ago and is not accepting any arguments which is probably erroneous. Your code should work well against 0-9-stable
. Try:
gem 'active_model_serializers', github: 'rails-api/active_model_serializers', branch: '0-9-stable'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.