rails – how to render a JSON object in a view

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!

  • An error occurred while installing eventmachine (1.0.3), and Bundler cannot continue
  • rails server Error : yld: lazy symbol binding failed: Symbol not found: _mysql_get_client_info
  • Ruby/Rails: Converting datetime to natural language (e.g. 3/23/2012 to “this Friday”)
  • creating a form for deleting uploads that belongs to products
  • mysql-2.8.1 gem error
  • Ruby on Rails - Carrierwave get the image dimension width and height
  • Rails.cache.read returns nil in rails, but not in console
  • Faraday::ConnectionFailed, Connection refused - connect(2) for “localhost” port 9200 Error Ruby on Rails
  • 3 Solutions collect form web for “rails – how to render a JSON object in a view”

    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) %>
    

    Or use:

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

    to escape out any html encoding characters.

    <%= @comments.to_json %>
    

    should do the trick too.

    Ruby is the best programming language in the world - Ruby on Rails.