rails 3 - 如何将PARTIAL呈现为Json响应

时间:2011-01-26 22:05:14

标签: ruby-on-rails ruby-on-rails-3

我想做这样的事情:

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

有办法做到这一点吗?在JSON对象中渲染部分?感谢

3 个答案:

答案 0 :(得分:42)

这应该有效:

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

注意 render_to_string 和下划线_在部分名称之前(因为render_to_string不期望部分,因此:layout =&gt; false < / strong>也是。)


<强>更新

如果您想在html请求中呈现json,我建议您在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

然后你可以在你的方法中做到这一点:

def upload
  with_format :html do
    @html_content = render_to_string partial: 'messages/_attachment', :locals => { :message => @message }
  end
  render :json => { :attachmentPartial => @html_content }
end

答案 1 :(得分:3)

这个问题有点陈旧,但我认为这可能对某些人有所帮助。

要在 json 响应中呈现 html 部分,您实际上并不需要{mbillard的答案中所述的with_format帮助器。您只需在调用render_to_string时指定格式,例如formats: :html

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

答案 2 :(得分:1)

在Rails 6中,我认为这可能与公认的答案有些不同。我认为您不需要在部分名称中设置下划线。这对我有用:

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