【问题标题】:Rails ActionView::MissingTemplate with Devise in API mode (format: json)Rails ActionView::MissingTemplate with Devise API 模式(格式:json)
【发布时间】:2020-09-26 08:43:02
【问题描述】:

当我将请求设置为 /api/v1/users/#{user.id}.json 时,我收到来自 Devise 的错误

Missing template api/v1/devise/registrations/edit, devise/registrations/edit, devise/edit, application/edit with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}

但我的应用程序在 API 模式下运行,我希望它返回一个 json 用户对象

设计控制器父类为:

Devise.setup do |config|
  config.parent_controller = 'Api::V1::StoreController'
end

存储控制器:

module Api
  module V1
    class StoreController < ApplicationController
    end
  end
end

和应用控制器:

class ApplicationController < ActionController::API
end

我如何使用 Devise 做到这一点?在所有其他控制器(非设计)中,它运行良好,总是返回一个 json 对象。

【问题讨论】:

    标签: ruby-on-rails json ruby devise


    【解决方案1】:

    您可以这样做以指定路线的默认格式

    namespace :api, defaults: { format: :json } do
      namespace :v1
        devise_for :users
      end
    end
    

    我猜你在路由下创建了正确的 json 响应,例如在 /api/v1/users/sign_in 中有一个带有 json 响应的控制器。

    我能看到的另一件事是你试图做什么与设计无关,对于路由 /api/v1/users/:id 你必须有一个这样的控制器:

      class Api::V1::UsersController < ApplicationController
        before_action :authenticate_user!, only: :show
    
        def show
          render json: current_user, status: :ok
        end
      end
    

    【讨论】:

    • 是的,我确信它可以工作,但我想用默认的设计控制器而不是自定义控制器来做到这一点。
    【解决方案2】:

    我也在寻找合适的解决方案,但尚未成功。但是,我通过如下渲染在this topic 中找到了解决方法

    render plain: your_json_object.to_json, content_type: 'application/json'
    

    它也适用于默认设计控制器。

    【讨论】:

      猜你喜欢
      • 2020-03-03
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多