渲染json的Rails破坏不起作用

时间:2018-03-17 08:26:44

标签: ruby-on-rails

我试图根据破坏是否有效来渲染一些特定的json。但是,代码超过@attachment.destroy ...然后在尝试渲染json时抛出异常。不确定这里发生了什么。

  def delete
    @attachment = Attachment.find(params[:attachment_id])

    if @attachment.destroy
      render json: {
        status: 200,
        message: MESSAGES_SUCCESS
      }
    else
      render json: {
        status: 422,
        message: MESSAGES_FAILED
      }
    end
  end

1 个答案:

答案 0 :(得分:1)

销毁附件,然后检查是否有任何错误。

def delete
    @attachment = Attachment.find(params[:attachment_id])
    @attachment.destroy

    if @attachment.errors.any?
        render json: {
            status: :unprocessable_entity, # 422
            message: MESSAGES_FAILED
        }
    else
        render json: {
            status: :ok, # 200
            message: MESSAGES_SUCCESS
        }
    end
end