我的应用程序中有一个模型事件,我有两个问题,第一个是返回的json与请求混淆:
$ curl http://0.0.0.0:3000/events
它给了我
{
"events":[
{"events":{"name":"First"}},
{"events":{"name":"Second"}}],
"meta":{"total_pages":9,
"next_page":"http://0.0.0.0:3000/events?page=2"}
}
我认为它应该给出
{
"events":[
{"name":"First" },
{"name":"Second"}
],
"meta":{
"total_pages":9,
"next_page":"http://0.0.0.0:3000/events?page=2"
}
}
我也使用gems draper和active_model_serializer,第二个问题是json格式不尊重Serializer定义:
class EventSerializer < ActiveModel::Serializer
attributes :id, :date_end
end
我想知道在哪里可以解决这些问题。
回答问题,生成json的代码:
class EventsController < ApplicationController
def index
@events = Event.order(:name).page(params[:page])
@events = @events.where(id: params[:ids].split(',')) if params[:ids].present?
render json: @events.decorate, meta: { total_pages: @events.total_pages, next_page: next_page_url(@events)}
end
def next_page_url(event)
unless event.last_page?
next_page = event.current_page + 1 unless event.last_page?
events_url(params.merge({:page => next_page}))
end
end
和装饰者:
class EventDecorator < Draper::Decorator
delegate :current_page, :total_pages, :limit_value
def name
object.name
end
end