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
我的 ListView 渲染工作正常,但是当我想做一个显示 View 时,有两个对象,并且带有包含的显示不会渲染正确的 JSON。它用 include 引用对象中的所有内容......
JSON 输出如下所示:
showring => "{"available":"yes","eng...9","stone_y":"149.4"}]}"
other_rings => 正确渲染的对象
另外,如果我已经将 include 添加到 @rings 对象,为什么我又必须在“to_json”方法中添加关联?
最佳答案
当你做的时候
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
完成了将对象转换为哈希的所有工作,但没有转换为字符串的最后一步
关于ruby-on-rails - RAILS3 : to_JSON with multiple objects and includes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265530/