RAILS3:to_JSON包含多个对象

Joe*_*nas 1 activerecord json jsonp ruby-on-rails ruby-on-rails-3

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
Run Code Online (Sandbox Code Playgroud)

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

JSON输出如下所示:

showring =>"{"available":"yes","eng ... 9","stone_y":"149.4"}]}"

other_rings =>正确渲染的对象


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

Fre*_*ung 9

当你这样做

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

Rails将@showring转换为json(即返回字符串表示),即值是字符串文字.相反

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

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