Rails Thumbnail


Using RABL to Display Multiple Models

22 Mar , 2012  

I had a scenario where I needed to show a collection of tweets AND a hash of stats related to those tweets,using RABL, a nice Rails Gem useful for displaying JSON-formatted data. Unfortunately, I couldn’t find enough good examples on how to do this–and after some frustrating hours learned that RABL doesn’t play well with hashes.

In this example I have a model, @tweets, filled with scraped tweets from Twitter. I have a hash, stats, filled with stats about those tweets–like the total number, the number of tweeters, the number of re-tweets, etc. Ideally, I’d like my JSON response to look something like:

{"stats":{"total":1024,"users":128,"retweets":"32"},"tweets":[{"tweet":"Petrol heads! Tune in to @DiscoveryUK at 9PM for the premiere of brand new #WheelerDealers the series kicks off with a rather nice Fiat Dino"},{"tweet":"2nd last nite in bahamas!  Dinner alone. shark diving done and my camera gear just arrived!!  Thanks a lot Air Canada. Exmas tmrw.  L"}...]}

First, in your controller, convert this hash to an OpenStruct format, which uses a RABL-friendly dot notation, like


require 'ostruct'
@stats = OpenStruct.new
@stats.total = @tweets.count
@stats.users = '128'  # Keep adding stats if you'd like
@stats.retweets = '32' # .. more stats

Then, in your view file


object false

child @stats => :stats do
  attribute :total, :users, :reteweets

child @tweets => :tweets do
  attributes :tweet

Your result should look like the example output above. Two things to note: 1) I was able to get this to work without explicitly requiring ostruct in my controller. 2) It also works without explicitly specifying “object false” in your .rabl file.