Rails 7 - CurrentAttributes - 不支持的参数类型

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

我的伪类 Current

class Current < ActiveSupport::CurrentAttributes
    attribute :user

end

我的应用程序控制器:

class ApplicationController < ActionController::Base

    before_action :set_current_user, if: :user_signed_in?

    private 
    
    def set_current_user
        Current.user = current_user
    end

end

我的班级房间:

class Room < ApplicationRecord

    def send_partial_counter_and_users_list
      broadcast_update_to('users_in_room_list', target: 
      'users_room_' + self.id.to_s, partial: 
      "rooms/users_in_room", locals: {users_in_room: 
      users_in_room_list })
    end

    def users_in_room_list

        user = User.find_by(Current.user)
        banned_by_me = Ban.where('user_id =?',user.id).pluck(:ban_id)
        users = User.where('id not in (?)',banned_by_me)
        @users = users
        @users
        
    end

  end

并在“查看”按钮中更新房间:

<% if @single_room %>
   <%= button_to '<i class="fa-solid fa-trash-arrow-up"> 
   </i>'.html_safe, room_path(@single_room.id), :method => 
    :delete%>
<% end %>

为什么我得到这个错误:

ArgumentError in RoomsController#destroy
Unsupported argument type: #<User:0x00007fabf9af8168> (User)
Extracted source (around line #28):
              
    def users_in_room_list

        user = User.find_by(Current.user)

它工作正常但是当我想在应用程序的其他部分对房间模型做更多的事情时,我看到了这个错误。来自房间模型的广播每 10 秒按计划运行一次,然后脚本不打印任何 user = User.find_by(Current.user) 错误,但是在应用程序其他部分的每次更新/删除等时,我看到这个,例如:

在消息类中我想更新房间状态-

Room.where('id =? and is_private =?',params[:room_id], 
true).update(:mark_as_closed => false)

这会为 MessagesController#create 生成错误:

Unsupported argument type: #<User:0x00007fabf9af8168> (User)
ruby-on-rails broadcast turbolinks ruby-on-rails-7 turbo
1个回答
0
投票

看起来用户对象已经加载所以你可以简单地做

banned_by_me = Ban.where(user_id: Current.user.id).pluck(:ban_id)

如果你真的想(重新)加载你可能想要的用户对象

User.find_by(id: Current.user.id)
© www.soinside.com 2019 - 2024. All rights reserved.