在没有模型的表NxN中计算记录

时间:2014-05-23 13:14:07

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

所以,我怀疑。

在我的应用程序中,我有一个名为user_profiles_mobile_models的表,这个表有两列: user_profile_id int(11)PK mobile_model_id int(11)PK

但我有两个模型,UserProfile和MobileModel。

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

我需要计算有多少用户拥有ID为1,7,8的移动模型...

它可能做到这一点?

谢谢,抱歉我的英语不好

1 个答案:

答案 0 :(得分:2)

如果您的模型MobileModel中有

has_and_belongs_to_many :user_profiles, join_table: 'user_profiles_mobile_models'

然后,我们可以使用。

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