18

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!

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

3 Answers3

27

Or use:

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

to escape out any html encoding characters.

JayCrossler
  • 2,079
  • 2
  • 22
  • 22
  • tested and it seems safe, e.g. `"` becomes `"\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e"` – Dorian Dec 14 '20 at 20:29
13

I would recommend that you write that code in an helper itself. Then just use the .to_json method on the array.

# application_helper.rb
def comments_as_json(comments)
  comments.collect do |comment|
    {
      :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.to_json
end

# your_view.html.erb
<%= comments_as_json(@conversation_comments) %>
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
  • Wait... Does being inside a helper mean that it can use things like simple_format, etc w/o needing includes? – AnApprentice Mar 01 '11 at 23:22
  • If I did this with the fact that html_format uses simple_format and auto_link be a problem? – AnApprentice Mar 01 '11 at 23:22
  • I assume you found that answer yourself by now - but yes, you don't need to explicitly include other helpers within a helper. Note: This requires that your ApplicationController has `helper :all` (default). – Marcel Jackwerth Mar 02 '11 at 00:32
7
<%= @comments.to_json %>

should do the trick too.

Stu Thompson
  • 38,370
  • 19
  • 110
  • 156
Daniel Tsadok
  • 573
  • 5
  • 10