Usage with jbuilder

Kate R edited this page Mar 16, 2017 · 9 revisions

Use gon with Jbuilder templates. It's similar in use to the Rabl integration:

  1. Add Jbuilder to the Gemfile before requiring gon, as gon checks the Jbuilder constant.
`Gemfile`

```ruby
gem 'jbuilder'
...
gem 'gon'
```
  1. Create Jbuilder template.
`app/views/posts/index.json.jbuilder`

``` jbuilder
json.posts @posts, :id, :title, :body
```
  1. In your controller you should just call 'gon.jbuilder' - if your template is in the default directory for the action. In the other cases - you still can use :template option to the jbuilder method.

With default template location

``` ruby
def index
  # some controller logic
  @posts = Post.all

  gon.jbuilder
  # some controller logic
end
```

With custom template location

``` ruby
def index
  # some controller logic
  @posts = Post.all

  gon.jbuilder template: 'app/views/posts/myposts.json.jbuilder',
  as: :my_posts

  # some controller logic
end
```

In javascript file for view of this action write call to your variable:

Now you can use partials in jbuilder:

app/views/posts/index.json.jbuilder

json.partial! 'posts/part', :comments => @posts[0].comments

app/views/posts/_part.json.jbuilder

json.comments comments.map{ |it| 'comment#' + it.id }
alert(gon.posts)
alert(gon.posts[0])
alert(gon.posts[0].post.body)
alert(gon.comments)
alert(gon.comments[0])

P.S. If you didn't put include_gon tag in your html head area - it wouldn't work. You can read about this in common usage above.