activerecord - Rails - Active Record: Find all records which have a count on has_many association with certain attributes -


a user has many identities.

class user < activerecord::base     has_many :identities end  class identity < activerecord::base     belongs_to :user end 

an identity has confirmed:boolean column. i'd query users have 1 identity. identity must confirmed false.

i've tried this

user.joins(:identities).group("users.id").having( 'count(user_id) = 1').where(identities: { confirmed: false }) 

but returns users 1 identity confirmed:false but have additional identities if confirmed true. want users 1 identity confirmed:false , no additional identities have confirmed attribute true.

i've tried it's slow , i'm looking right sql in 1 query.

  def self.new_users     users = user.joins(:identities).where(identities: { confirmed: false })     users.select { |user| user.identities.count == 1 }   end 

apologies upfront if answered not find similar post.

  def self.new_users     joins(:identities).group("identities.user_id").having("count(identities.user_id) = 1").where(identities: {confirmed: false}).uniq   end 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -