Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rabl json collection dynamic keys

I have a User model that has many posts. Im trying to render the post in a rabl collection.

collection @posts
attributes :title, :created_at

The default rabl format for rendering json collections is {'posts': ['post':{}, 'post':{}]} . What I'm trying to accomplish is to change the 'post' key to a dynamic value post id for instance, so that my format would look like so {'posts':[1:{}, 2:{} ]}. Was trying with the configure of Rabl but the only thing I found out is how to get rid of the collection key with

Rabl.configure do |config|
  config.include_json_root = false
end
like image 758
pkurek Avatar asked Feb 21 '23 02:02

pkurek


1 Answers

I don't think RABL currently supports this natively, but since RABL is nothing more than syntactic sugar on top of the ruby code base, you should be able to do this yourself by using a loop.

For example (I haven't tried this, but you should get the general gist):

collection @posts

@posts.each do |post|
  node(post.id.to_sym) {{ title: post.title, created_at: post.created_at }}
end
like image 82
JeanMertz Avatar answered Apr 19 '23 20:04

JeanMertz