Question

I'm using RABL as the foundation for a JSON API. I need to display both an object (@user) and a collection (@posts) in a template. Typically, this is no problem. @posts are a child of @user, so, I just do this:

object @user 
   attributes :id, :name
   child :posts do |post|...

The problem is, I run @posts through a helper method (by_category) in the controller like so:

@user = User.find(params[:id])
@posts = @user.posts.by_category(params[:category])

By just fetching the posts as a child node, I don't apply the helper method – and I can't fetch posts by_category.

I'm wondering how to best approach this, and if there's a way to display both an object and a collection in the same RABL template?

Was it helpful?

Solution

Right from the documentation, you can include locals in partials like this example:

You can also pass in other instance variables to be used in your template as:

Rabl::Renderer.new('posts/show', @post, :locals => { :custom_title => "Hello world!" })

Then, in your template, you can use @custom_title as:

attribute :content
node(:title) { @custom_title }

This allows you to use something like:

Controller:

Rabl::Renderer.new('user/show', @user, :locals => { :posts_category => "examples" })

Partial:

attribute id
node(:posts) { |user| user.posts.by_category(@posts_category) } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top