Ruby rails 中 as_json 的一些技巧

lhy20062008 · 2014年07月02日 · 最后由 torvaldsdb 回复于 2017年02月28日 · 3407 次阅读

as_json 是 Array 的方法,在 rails 中可以直接这样使用: user 包括以下字段:name, age users = User.first(10) users.as_json 当然也可以在 user.rb 中复写 as_json 方法: def as_json {name: name + "end", age: age + 1} end 这样,得到得就是新的值了;

甚至还可以对分组的 users 调用上面定义的 as_json users = users.group_by{|user| age > 18} users.as_json will get the result : { "true": [{name: 'dd', age: 29},{name: 'ddd',age: 23}], "false": [{name: 'dd', age: 12}, {name: 'dddd', age: 11}] } 这样可以大大简化代码

我用 group_by 以后的 hash 去 as_json 怎么就报错了呢 undefined method `key?' for #JSON::Ext::Generator::State:0x37e7db8

#1 楼 @birbird 看你怎么用的了,直接对 activerecord 对象数组或者 relation 调用 group_by 之后再调用 as_json 没问题。

针对Relation, HashArray都可以直接调用as_json. 通过group_by只是获得一个两层hash, 可以调用as_json是理所当然的事情吧。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号