[英]Devise Token Auth :authenticate_user! works wrong
If I add before_action :authenticate_user!
如果我添加before_action :authenticate_user!
to ApplicationController
, I get an error:到ApplicationController
,我收到一个错误:
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: json.data @users, :name, :username
What comes from this file:来自这个文件的内容:
show.jbuilder显示.jbuilder
json.data @users, :name, :username
My controller:我的控制器:
users_controller.rb用户控制器.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def index
@users = User.all
end
end
If I remove before_action :authenticate_user!
如果我删除before_action :authenticate_user!
everything works just fine, I get JSON object with the list of users.一切正常,我得到了带有用户列表的 JSON 对象。
Why does it happen?为什么会发生? Device usually returns 401
, but devise_token_auth
is trying to trigger my show
and fails because can't access database.设备通常返回401
,但devise_token_auth
试图触发我的show
并失败,因为无法访问数据库。 How to fix this weird behaviour?如何解决这种奇怪的行为?
Your controller is pretty idiosyncratic and your error is that you are sending a collection to a view that is built for a single resource.您的控制器非常特殊,您的错误是您将集合发送到为单个资源构建的视图。
In Rails the show action corresponds to viewing a single resource and usually relies on passing the ID via an :id
parameter:在 Rails 中,show 操作对应于查看单个资源,并且通常依赖于通过:id
参数传递 ID:
class UsersController < ApplicationController
# GET /users
def index
@users = User.all
end
# GET /users/:id
def show
@user = User.find(params[:id])
end
end
You don't need to explicitly call render either.您也不需要显式调用 render 。
app/views/users/show.json.jbuilder:应用程序/视图/用户/show.json.jbuilder:
json.(@user, :name, :username)
app/views/users/index.json.jbuilder:应用程序/视图/用户/index.json.jbuilder:
json.comments @user do |json, user|
json.(user, :name, :username)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.