如何干掉这个Rails API创建响应?

时间:2016-01-23 14:48:08

标签: ruby-on-rails api

以下代码字段对我来说非常冗长 - 有没有办法干这个?

    if @job.save
         respond_to do |format|
            format.xml {
               render xml: {error: "Job created successfully."}, status: 200
            }
           format.json {
               render json: {error: "Job created successfully."}, status: 200
            }
         end
      else
         respond_to do |format|
            format.xml {
               render xml: {error: @job.errors}, status: 422
            }
           format.json {
               render json: {error: @job.errors}, status: 422
            }
         end
      end

1 个答案:

答案 0 :(得分:1)

您可以使用respond_to and respond_with

class JobsController < ApplicationController
  respond_to :xml, :json

  def create
    if @job.save
      respond_with {error: "Job created successfully."}, status: 200
    else
      respond_with {error: @job.errors}, status: 422
    end
  end
end