ruby-on-rails - RAILS3 : to_JSON with multiple objects and includes

标签 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

我的 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/

相关文章:

ruby-on-rails - Redis.set 不使用下划线或连字符保存键,Redis.get 返回 nil

ruby-on-rails - 如何更新我的应用程序中的 Rails

PHP:按键对 JSON 数据进行排序

javascript - Angular ng-repeat 无法正确渲染数据

ajax - 如何从我的数据库数据生成实时 Highcharts ?

ruby-on-rails - rails 4 |使用位掩码在表单中为用户分配角色 |好榜样

javascript - 如何在 Rails 中的输入标签内存储 erb 值?

css - 更改导航丸的事件颜色

ruby-on-rails - 大学电子邮件 Rails 的电子邮件验证

ruby-on-rails - 橡胶无法用于Rails AWS部署