1

My pseudo class Current

class Current < ActiveSupport::CurrentAttributes
    attribute :user

end

My ApplicationController:

class ApplicationController < ActionController::Base

    before_action :set_current_user, if: :user_signed_in?

    private 
    
    def set_current_user
        Current.user = current_user
    end

end

My class Room:

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

And in View button to update room:

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

Why I get this error:

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)

It works fine but when I want to do somethin more with Room model in other part of app, I see this error. Broadcast from Room model is run in schedule every 10.seconds and then script do not print any user = User.find_by(Current.user) error, but on every update/delete etc. from other part of app, I see this, for example:

In messages class I want to update room status -

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

and this generate error for MessagesController#create:

Unsupported argument type: #<User:0x00007fabf9af8168> (User)
Wordica
  • 2,427
  • 3
  • 31
  • 51

1 Answers1

0

Looks like the user object is already loaded so you can simply do

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

If you actually want to (re)load the user object you probably want

User.find_by(id: Current.user.id)
Arctodus
  • 5,743
  • 3
  • 32
  • 44
  • NoMethodError: undefined method `id' for nil:NilClass for Current.user.id – Wordica May 01 '23 at 10:29
  • 1
    If `Current.user` is sometimes `nil` then using try operator is an option `Current.user&.id` – Arctodus May 01 '23 at 10:34
  • no, it doesnt work ... i trace with Rails.logged.fatal ... and : USER_Current.user&.id_ (no result) USER_Current.user_ # When I find_by(id:Current.user&.id) I have no results, for find_by(Current.user) I got current_user in result – Wordica May 01 '23 at 13:26