Home > Blockchain >  Handle selection via has_many in Rails 6
Handle selection via has_many in Rails 6

Time:06-09

I’m new to Rails development and I’m trying to build a simple messenger app with basic functionality. The app has three models: User, Message, and Room. There is a relation between rooms and users:

class Room < ApplicationRecord
  has_many :messages
  has_many :users, through: :messages
end

Also, the Message model looks like this:

class Message < ApplicationRecord
  belongs_to :user
  belongs_to :room
end

The question is: how do I select all messages that belong to all the rooms my current_user is member of with ActiveRecord?

For example, if my user is in room 1 with messages 1, 2, 3 and in room 2 with messages 4, 5, 6, but he is only the author of messages 1 and 4, I need to select all 6 messages.

I could only achieve this through a for-loop which is the ugliest and most inefficient way.

CodePudding user response:

Add to your User model these three associations

class User < ApplicationRecord
  has_many :messages
  has_many :rooms, through: :messages
  has_many :all_messages, through: :rooms, class_name: 'Message', source: :messages
end

And in your code you can use following:

current_user.all_messages
  • Related