Search code examples
ruby-on-railsrubyenumeration

Rails Counting Child Models Conditionally


So I have an app where a User has many posts. Those posts can either be published or drafted. I have this setup through an enumeration, it looks like this:

class User < ActiveRecord::Base
  has_many :posts
end

The Post model:

class Posts < ActiveRecord::Base
  belongs_to :user 
  enum draft_status: [:draft, :published]
end

I'd like to set a controller variable that only returns Users who have any published pieces. How would I set such a variable?

I have tried:

@bloggers = User.all.where('posts.published.any? =', true)

That didn't work any idea how I would define this?


Solution

  • You can use this, for example:

    @bloggers = User.where(id: Post.published.uniq.pluck(:user_id))