Ruby on rails RAILS3:使用多个对象和包含

Ruby on rails RAILS3:使用多个对象和包含,ruby-on-rails,ruby-on-rails-3,json,activerecord,jsonp,Ruby On Rails,Ruby On Rails 3,Json,Activerecord,Jsonp,我的列表视图呈现效果很好,但是当我想要使用两个对象显示视图,并且使用includes显示时,不会呈现正确的JSON。它引用对象中的所有内容,包括 JSON输出如下所示: showring=>“{”可用“:“是”,“工程…9”,“石头y:“149.4}]}” 其他_环=>正确渲染的对象 另一方面,如果我已经将includes添加到@rings对象中,那么为什么还要在“to_json”方法中添加关联呢 def list @rings = Ring.order("RAND()") #

我的列表视图呈现效果很好,但是当我想要使用两个对象显示视图,并且使用includes显示时,不会呈现正确的JSON。它引用对象中的所有内容,包括

JSON输出如下所示:

showring=>“{”可用“:“是”,“工程…9”,“石头y:“149.4}]}”

其他_环=>正确渲染的对象


另一方面,如果我已经将includes添加到@rings对象中,那么为什么还要在“to_json”方法中添加关联呢

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
Rails正在将@showring转换为json(即返回字符串表示),即值是字符串文本。取而代之的是

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

由于_json
完成了将对象转换为散列的所有工作,但没有将对象转换为字符串的最后一步

如果您打算投入更多时间构建更多的json对象,您应该研究一个名为rabl的gem。它使构建JSON变得非常简单,有利于定制,从而有利于构建API

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