0

I have a post and comment model. A post has many comments. What I want to do is have a query that checks for posts where the last comment description is empty.

class Post < ActiveRecord::Base
   has_many :comments
end


class Comment < ActiveRecord::Base
   belongs_to :post
end

Without sql, this would look like this:

Post.all.select { |p| p.comments.last.description == "" }

N.B: This is a rails 3.2 application. where.not does not work in this case

Adim
  • 1,716
  • 12
  • 13
  • I think you can find some answers here: https://stackoverflow.com/questions/5319400/want-to-find-records-with-no-associated-records-in-rails-3 – trueunlessfalse Oct 08 '18 at 08:19
  • @trueunlessfalse I updated the question to more closely mirror my problem. I don't think my answer is in this link – Adim Oct 08 '18 at 08:38
  • 1
    Okay, you're right, that is a different issue. I can not think of an easy way of doing it with active record. This looks helpful though: https://stackoverflow.com/questions/5247886/rails-query-through-association-limited-to-most-recent-record – trueunlessfalse Oct 08 '18 at 08:48
  • Even in your non-sql solution you should explicitly specify the order before calling last. – trueunlessfalse Oct 08 '18 at 08:49

0 Answers0