문제

I am sure this might be a stretch but I'm very impressed with the flexibility that Active Model Serializers provide. I'd like to something like:

 def by_location_and_bin_number
    @items=MenuItem.where('bin_number=? and location_id=?', params[:bin_number], params[:location_id]).is_valid
    r={}
    r[:status]="success"
    r[:count] = @tems.count
    r[:menu_items] = @items, serializer: ItemMicroSerializer # <- not working
    render json: r.to_json
  end

but this doesn't work. How can I get this to work (or similar syntax)?

도움이 되었습니까?

해결책

As you want to serialize the array @items, you can use the independent method as

r[:menu_items] = ActiveModel::ArraySerializer.new(@items, each_serializer: ItemMicroSerializer)

It will serialize the provided array of objects by serializing each object using ItemMicroSerializer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top