27

I want to do something like this:

class AttachmentsController < ApplicationController
  def upload
    render :json => { :attachmentPartial => render :partial => 'messages/attachment', :locals => { :message=> @message} }
  end

Is there a way to do this? render a Partial inside a JSON object? thanks

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

3 Answers3

44

This should work:

def upload
    render :json => { :attachmentPartial => render_to_string('messages/_attachment', :layout => false, :locals => { :message => @message }) }
end

Notice the render_to_string and the underscore _ in before the name of the partial (because render_to_string doesn't expect a partial, hence the :layout => false too).


UPDATE

If you want to render html inside a json request for example, I suggest you add something like this in application_helper.rb:

# execute a block with a different format (ex: an html partial while in an ajax request)
def with_format(format, &block)
  old_formats = formats
  self.formats = [format]
  block.call
  self.formats = old_formats
  nil
end

Then you can just do this in your method:

def upload
  with_format :html do
    @html_content = render_to_string partial: 'messages/_attachment', :locals => { :message => @message }
  end
  render :json => { :attachmentPartial => @html_content }
end
mbillard
  • 38,386
  • 18
  • 74
  • 98
  • 4
    Just thought I would mention that mbillard's solution only found the partial for me after I added the `.html` postfix to the partial path , I think this might be because it was using a json format by default. – Noz Dec 05 '12 at 21:43
  • @CyleHunter that's actually a pretty common use case, I edited my answer to cover this behavior. – mbillard Dec 05 '12 at 21:50
  • 1
    Rails 3.2: You can also set the handler (haml, erb, etc.) in render_to_string, e.g. render_to_string(partial: 'messages/attachment', handlers: [:haml]) – Luke W Jan 03 '13 at 19:53
12

This question is a bit old, but I thought this might help some folks.

To render an html partial in a json response, you don't actually need the with_format helper as explained in mbillard's answer. You simply need to specify the format in the call to render_to_string, like formats: :html.

def upload
  render json: { 
    attachmentPartial: 
      render_to_string(
        partial: 'messages/attachment', 
        formats: :html, 
        layout: false, 
        locals: { message: @message }
      )
  }
end
jibai31
  • 1,663
  • 18
  • 22
1

In Rails 6 I think this might be a little different from the accepted answer. I don't think you need to set the underscore in the partial name. This worked for me:

format.json {
  html_content = render_to_string(partial: 'admin/pages/content', locals: { page: @page }, layout: false, formats: [:html])
  render json: { attachmentPartial: html_content }
}
Dylan Fisher
  • 316
  • 3
  • 8