Rails nested querying through another association

I have the following active record models:

class Jobs
  has_many :leads
end

class Lead
  has_many :messages, through :notification
end

class Notification
  has_many :messages
end

class Message
  # has a type column (varchar) containing either: email, sms
end

I am unsure about how to find all jobs which through its associations have messages which are not of type sms. Is this even possible to do?

Upvotes: 0

Views: 42

Answers (2)

WVU2001
WVU2001

Reputation: 41

As Bruno and Jedi pointed out, something like this may work:

Job.joins(leads: [{ notifications: :message }]).where.not(messages: {msg_type: 'sms'})

Note this uses singular model name for Job (not Jobs). And associations like:

class Job < ApplicationRecord
  has_many :leads
end

class Lead < ApplicationRecord
  belongs_to :job
  has_many :notifications
  has_many :messages, through: :notifications
end

class Notification < ApplicationRecord
  belongs_to :lead
  belongs_to :message
end

class Message < ApplicationRecord
  has_many :notifications
  has_many :leads, through: :notifications
end

Not clear from your question whether you have all those associations set properly.

Upvotes: 1

Bruno
Bruno

Reputation: 389

You could join your tables and set a where clause in order to filter those messages that are not sms.

May be something like this:

Jobs.joins(leads: [{ notifications: :messages }]).where("type <> 'sms'")

Check https://guides.rubyonrails.org/active_record_querying.html#joining-tables for more information.

Upvotes: 3

Related Questions