Rabl json收集动态键

时间:2012-06-21 11:59:37

标签: ruby-on-rails ruby rabl

我有一个包含很多帖子的用户模型。我试图在一个rabl集合中发布帖子。

collection @posts
attributes :title, :created_at

渲染json集合的默认rabl格式是 {'posts': ['post':{}, 'post':{}]}。我想要完成的是改变帖子'例如,动态值post id的关键,因此我的格式看起来像{'posts':[1:{}, 2:{} ]}。尝试使用Rabl的配置,但我发现的唯一的事情是如何摆脱

的集合键
Rabl.configure do |config|
  config.include_json_root = false
end

1 个答案:

答案 0 :(得分:8)

我不认为RABL本身支持这种方式,但由于RABL只不过是在ruby代码库之上的语法糖,你应该能够通过循环来自己完成。

例如(我没试过这个,但你应该得到一般的要点):

collection @posts

@posts.each do |post|
  node(post.id.to_sym) {{ title: post.title, created_at: post.created_at }}
end