Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Count records in a table NxN without model


So, I'm a doubt.

In my app, I have a table called user_profiles_mobile_models, this table have two columns: user_profile_id int(11) PK mobile_model_id int(11) PK

But I have two models, UserProfile and MobileModel.

class UserProfile
  ...
  has_and_belongs_to_many :mobile_models, join_table: 'user_profiles_mobile_models', order: 'name'
  ...

I need count how many users have a mobile model with id 1,7,8...

Its possible do that?

Thanks and sorry for my poor english


Solution

  • If in your model MobileModel you have a

    has_and_belongs_to_many :user_profiles, join_table: 'user_profiles_mobile_models'
    

    Then, we can use.

    MobileModel.where('id in (?)', [1,7,8]).map(&:user_profiles).count