Json Jbuilder v/s render :json method

Viewed 914

While trying to send json responses, what are the benefits that one might have using render method over jbuilder or vice-versa.

For Example:

render :json=> @boats

v/s

In index.json.jbuilder

json.array! @boats do |boat|   
    json.boat_name boat.name 
end

I tried using both the ways, but could not find any significant advantage of one over the other. The reason might be that my application is small. So i wanted to know if there was any difference between them at all in large scale applications.

1 Answers

Jbuilder provides a DSL for generating JSON. It includes a template engine which allows you to create complex responses with helpers and conditions.

example

We could add this without using JBuilder by adding a render

def show
  @article = Article.find(params[:id])
   render json: @article 
end

When we reload the page now we’ll see the JSON representation of the article.

{"author_id":1, title:"hello", etc}

enter image description here if you want Customizing The Response can use as_json like

   format.json { render json: @article.as_json(only: [:id, :name, :content], include: [:author, {comments: {only:[:id, :name, :content]}}]) }

Customizing The Response can use <code>as_json</code>

Using JBuilder This works, but the code we’ve used isn’t very pretty. We could override as_json in the model but this wouldn’t be much prettier.

json.id @article.id
json.name @article.name

enter image description here

can use any customize in JBuilder

Thanks for railscasts can read for more information

Related