rails - how to render a JSON object in a view

AnApprentice picture AnApprentice · Mar 2, 2011 · Viewed 26.6k times · Source

right now I'm creating an array and using:

render :json => @comments

This would be fine for a simple JSON object, but right now my JSON object requires several helpers which is breaking everything and requiring helper includes in the controller which seems to cause more problems than solved.

So, how can I create this JSON object in a view, where I don't have to worry about doing anything or breaking anything when using a helper. Right now the way I'm making the JSON object in the controller looks little something like this? Help me migrate it to a view :)

# Build the JSON Search Normalized Object
@comments = Array.new

@conversation_comments.each do |comment|
  @comments << {
    :id => comment.id,
    :level => comment.level,
    :content => html_format(comment.content),
    :parent_id => comment.parent_id,
    :user_id => comment.user_id,
    :created_at => comment.created_at
  }
end

render :json => @comments

Thanks!

Answer

JayCrossler picture JayCrossler · Jan 27, 2013

Or use:

<%= raw(@comments.to_json) %> 

to escape out any html encoding characters.