respond_with - 如何回复文本

And*_*res 6 ruby-on-rails

我在rails应用程序中使用了respond_to和respond_with,但是在一个用例中我只需要响应一种资源格式的文本(:json)......但是我找不到怎么做...

我想要这样的东西(我知道这不起作用)

def create
    ...
    respond_with(:json, render :text => "Successfully Done!")
end
Run Code Online (Sandbox Code Playgroud)

任何的想法??

谢谢!

Max*_*unn 10

看来这可能就是你要找的东西:

def create
  respond_to do |format|
    format.html
    format.json { render :text => "Successfully Done!" }
  end
end
Run Code Online (Sandbox Code Playgroud)


Bru*_*ira 8

安德烈斯,

解决方案是这样的:

class TextController < ApplicationController
  respond_to :json, :text

  def index
    respond_with do |format|
      format.json {
        render :text => "I'm a text provided by json format"
      }
      format.text {
        render :text => "I'm a text"
      }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

并在您的routes.rb:

match '/text' => 'text#index', defaults: { format: 'text' }
Run Code Online (Sandbox Code Playgroud)