RAILS3:to_JSON包含多个对象

时间:2012-09-04 14:22:27

标签: ruby-on-rails ruby-on-rails-3 json activerecord jsonp

def list
    @rings = Ring.order("RAND()")
    #JSON RENDERING
    render :json => @rings.to_json(:include => [:variations, :stones]), :callback => params[:callback]
end

def show
    @showring = Ring.includes(:stones, :variations).find(params[:id])
    @other_rings = Ring.select([:id, :stone_count]).where(:style_number => @showring.style_number).reject{ |ring| ring == @showring}
    #JSON RENDERING
    render :json => {@showring.to_json(:include =>[:variations, :stones]), :other_rings => @other_rings}, :callback => params[:callback]
end

我的列表视图渲染工作正常,但是当我想要使用两个对象进行展示视图时,使用包括展示将无法呈现正确的JSON。它使用包含引用对象中的所有内容......

JSON输出如下所示:

showring => “{” 可用 “:” 是 “ ”主机... 9“, ”stone_y“: ”149.4“}]}”

other_rings =>正确渲染的对象


单独注意,如果我已经将包含添加到@rings对象,为什么我再次必须在“to_json”方法中添加关联?

2 个答案:

答案 0 :(得分:8)

当你这样做时

render :json => {:show_ring => @showring.to_json(:include =>[:variations, :stones]), :other_rings => @other_rings}

Rails正在将@showring转换为json(即返回一个字符串表示),即该值是字符串文字。而是做

render :json => {:show_ring => @showring.as_json(:include =>[:variations, :stones]), :other_rings => @other_rings}

as_json完成将对象转换为哈希的所有工作,但没有最后一步变成字符串

答案 1 :(得分:1)

如果你打算花更多的时间来构建更多的JSON对象,你应该研究一个名为rabl的gem。它使构建JSON变得非常简单,有利于自定义,这对于构建API非常有用。

相关问题