我使用 mongoid 作为我的 orm,我在结果集上调用 to_json。最初的实现工作正常,除了所有内容都是动态加载的(而不是预先加载)
简化的架构和代码如下:
Answer has_many likers
all_answers=Answer.includes(:likers).all.map{|a| a}
all_answer.to_json(:only=>[:text],:include => {:likers=>{:only=>[:_id,:nickname]}})
我开始使用这个很棒的 gem ( mongoid_eager_loading ),而且效果很好。但是,当我在结果集上调用 to_json 时
all_answers=Answer.includes(:user, :question,:likers,:comments).all.map{|a| a}
all_answer.to_json(:only=>[:text],:include => {:likers=>{:only=>[:_id,:nickname]}})
我会得到这个错误:
undefined method `serializable_hash' for #<Array:0x00000105b3d020>
此错误仅在我尝试包含一个数组时发生,例如:Answer has_many likers。
我怀疑单个对象中包含的数组没有 serializable_hash 方法。
我该如何解决这个问题?任何想法将不胜感激!
最佳答案
看看这篇来自 Miso Engineering 的帖子:
http://engineering.gomiso.com/2011/05/16/if-youre-using-to_json-youre-doing-it-wrong/
如果您将模型作为 JSON 推出,RABL gem ( https://github.com/nesquena/rabl) 值得一看。
关于ruby-on-rails - 数组的未定义方法 `serializable_hash',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6868869/