【问题标题】:Rails render doesn't workRails 渲染不起作用
【发布时间】:2015-01-09 05:05:17
【问题描述】:

我正在尝试从 rails 控制器返回一个 json 值,但奇怪的是它不起作用并且总是需要 html 格式。这是我的控制器方法:

  def result
        @command = params[:output]
        @result = []
        IO.popen("free -m") { |f| f.each { |e| @result << e } }
    rescue Errno::ENOENT
        @result << "No command found"

    render json: @result.to_json
  end

在我尝试访问此页面后,我收到了这种错误: MainController#result 作为 HTML 处理

ActionView::MissingTemplate (Missing template main/result, application/result with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}. Searched in:
  * "/home/vyivrain/Documents/RubyProjects/Diploma/app/views"

为什么它只需要 html 格式。我也尝试做 respond_to 或不渲染或渲染平原,但它给出了相同的结果。顺便说一下,我的 rails 版本是 4.1.5。所以有点奇怪。谢谢你的回答。

【问题讨论】:

    标签: ruby-on-rails json render


    【解决方案1】:

    改成这样:

      def result
        begin
            @command = params[:output]
            @result = []
            IO.popen("free -m") { |f| f.each { |e| @result << e } }
        rescue Errno::ENOENT
            @result << "No command found"
        end
    
        render json: @result.to_json
      end
    

    【讨论】:

    • 是的,你是对的,只是一个容易忘记的记忆,如果你指定开始/结束,救援覆盖代码块,否则覆盖整个方法。谢谢
    【解决方案2】:

    当您单击重定向到result 操作的链接时,请尝试指定:remote =&gt; true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多