0

I have these models

class User < ActiveRecord::Base
   has_and_belongs_to_many :chats
end

and

class Chat < ActiveRecord::Base
   has_and_belongs_to_many :users
end

Which is a many_to_many relationship and what I want is to recover the only possible chat that exists with 2 users

eg.

me = current_user
user_to_chat = User.find(any_user_except_me)

chat = Chat.new

me.chats.each do |current_chat|
  if current_chat.users.include?(user_to_chat)
    chat = current_chat
    break
  end
end

What is the better way to do this query?

thx!

Fabricioraphael
  • 195
  • 1
  • 9

1 Answers1

1

You can use #find which will return the first item in the collection for which the block is not false.

chat = me.chats.find { |c| c.users.include?(user_to_chat) }

You could also use intersections:

chat = (me.chats & user_to_chat.chats).first
Yanis Vieilly
  • 827
  • 6
  • 11