Rails 7 - CurrentAttributes undefined

问题描述 投票:0回答:1

有人能解释一下为什么吗:

 after_commit :send_partial_

 def send_partial_
  
   broadcast_update_to( ... locals:users_in_room_list )

 end
 

 def users_in_room_list

  user = User.find_by(id:Current.user.id)  // return undefined method `id' for 
  nil:NilClass

  user_name =  User.find_by(Current.user) // return <User:0x00007fbecc0dcf40>

 end

为什么我得到

undefined method 'id' for nil:NilClass
user
但我得到正确的数据
user_name
??

ruby-on-rails broadcast turbolinks ruby-on-rails-7 turbo
1个回答
0
投票

你的Current.user是nil(意思是没有内容)

如果你问 user_name = User.find_by(Current.user) 这个语句导致一个用户你可以试试这个代码

  x = nil
  user_name = User.find_by(x)
  # this will run query as follow
  SELECT "users".* FROM "users" LIMIT $1  [["LIMIT", 1]]

编辑2:

根据您之前的问题您的源代码

  class ApplicationController < ActionController::Base

    before_action :set_current_user, if: :user_signed_in?

    private 
    
    def set_current_user
        Current.user = current_user
      # this variable current_user is nil
      # that's why your Current.user = nil
    end

  end

© www.soinside.com 2019 - 2024. All rights reserved.