Rails XML构建器未呈现 [英] Rails XML builder not rendering

查看:55
本文介绍了Rails XML构建器未呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 4应用程序的请求响应正文中呈现XML时遇到问题。在下面的示例中,响应主体为空白。我已经在模板中放置了调试器,所以我知道它会在模板中运行,但是不会渲染任何东西。

I’m having an issue rendering XML in the response body of a request in a Rails 4 application. In the example below the response body is blank. I’ve put a debugger in the template so I know it runs through it but doesn’t render anything out.

我创建了一个简单的Rails应用程序来演示这个问题正在使用生成器返回xml。谁能指出我这个示例的问题(可能是愚蠢的简单问题)?

I created a simple rails app to demonstrate the issue I’m having using builder to return xml. Can anyone point me to the (probably stupid simple) problem with this example?

以下是控制器,模板和测试:

Here are the controller, template, and test:

controllers / bars_controller.rb

controllers/bars_controller.rb

require 'builder'

class BarsController < ApplicationController
  before_action :set_bar, only: [:show]

  # GET /bars/1
  # GET /bars/1.json
  def show
    @xml = Builder::XmlMarkup.new
    render template: 'bars/show.xml.builder', formats: [:xml]
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_bar
      @bar = Bar.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def bar_params
      params.require(:bar).permit(:foo, :bar)
    end
 end

/views/bars/show.xml.builder

/views/bars/show.xml.builder

@xml.instruct!
@xml.bar do
  @xml.foo(@bar.foo)
  @xml.bar(@bar.bar)
end

/test/controllers/bars_controller_test.rb

/test/controllers/bars_controller_test.rb

 require 'test_helper'

 class BarsControllerTest < ActionController::TestCase
  setup do
    @bar = bars(:one)
  end

  test "should show bar" do
    get :show, id: @bar
    assert_response :success
    assert_match "<bar>", response.body
  end
 end

调试会话

     1: @xml.instruct!
     2: binding.pry
  => 3: @xml.bar do
     4:   @xml.foo(@bar.foo)
     5:   @xml.bar(@bar.bar)
     6: end

     [2] pry(#<#<Class:0x007fc669e9f610>>)> @xml.bar do
     [2] pry(#<#<Class:0x007fc669e9f610>>)*   @xml.foo(@bar.foo)  
     [2] pry(#<#<Class:0x007fc669e9f610>>)*   @xml.bar(@bar.bar)  
     [2] pry(#<#<Class:0x007fc669e9f610>>)* end  
      => "<?xml version=\"1.0\" encoding=\"UTF-8\"?><bar><foo>MyString</foo><bar>MyString</bar></bar>"


推荐答案

看起来就像创建<$ c的实例$ c> Builder :: XmlMarkup.new 是您的问题。删除显式创建的生成器,使您的控制器如下所示:

It looks like creating the instance of the Builder::XmlMarkup.new is your problem. Remove the explicit creation of the builder so your controller looks like this:

def show
  # You can also simplify by removing "bars/"
  render 'bars/show.xml.builder', formats: [:xml]
end

您的视图应如下所示:

xml.instruct!
xml.bar do
  xml.foo(@bar.foo)
  xml.bar(@bar.bar)
end

这篇关于Rails XML构建器未呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆