1

I defined a User Model and a Message Model:

with User:

has many: messages

and Message:

belongs_to: user

I know how to get the users Messages:

 @users = User.all
 @users.messages

But how can i get all Users that have Messages and all Users that dont have Messages? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109
  • Have a look here: http://guides.rubyonrails.org/active_record_querying.html. There are examples on that page for doing this kind of data retrieval. – Robert Harvey Jun 03 '14 at 16:05

2 Answers2

2

You can use the .includes method:

users_without_messages = User.includes(:messages).where(messages: { id: nil })

users_with_messages = User.includes(:messages).where('messages.id IS NOT NULL')
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
1

A SQL-ish answer:

But how can i get all Users that have Messages

User.where('id IN (SELECT DISTINCT(user_id) FROM messages)')

and all Users that dont have Messages? Thanks

User.where('id NOT IN (SELECT DISTINCT(user_id) FROM messages)')
joni
  • 5,402
  • 1
  • 27
  • 40
  • also, look here (http://stackoverflow.com/questions/5319400/want-to-find-records-with-no-associated-records-in-rails-3) for a better answer using joins. – joni Jun 03 '14 at 16:09