简体   繁体   English

根据HABTM关联计数在Rails中创建范围

[英]Create a scope in rails based on HABTM association count

I'm trying to create a rails scope based on the count of a model's HABTM assocation, but I'm struggling with the SQL. 我正在尝试根据模型的HABTM关联数创建一个Rails范围,但是我在SQL方面苦苦挣扎。

I want Match.open to return matches with less than two users. 我希望Match.open返回少于两个用户的匹配。 I also have Match.upcoming, which returns matches with a 'future_date' in the future, which is working well. 我也有Match.upcoming,它将在将来返回带有'future_date'的匹配项,并且运行良好。

My code: 我的代码:

class Match < ActiveRecord::Base
  has_and_belongs_to_many :users

  scope :open, joins('matches_users').
      select('*').
      group('matches.id').
      having('count(matches_users.user_id) < 2')


scope :upcoming, lambda {
    where("proposed_date between ? and ?", Date.today, Date.today.next_month.beginning_of_month)
}

I'm currently getting the error: 我目前收到错误消息:

SQLite3::SQLException: no such column: matches_users.user_id: SELECT * FROM "matches" matches_users GROUP BY matches.id HAVING count(matches_users.user_id) < 2

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: matches_users.user_id: SELECT * FROM "matches" matches_users GROUP BY matches.id HAVING count(matches_users.user_id) < 2 ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:否这样的列:matchs_users.user_id:SELECT * FROM“ matches” matchs_users GROUP BY matchs.id HAVING count(matches_users.user_id)<2

I'm currently achieving this with a class method: 我目前正在使用类方法来实现此目的:

def self.open
    self.select{|match| match.users.length < 2}
end

Which works, but I'd really like to move this into a scope for speed, and so that I can chain the scopes like Match.open.upcoming. 哪个可行,但我真的很想将其移到速度范围内,以便可以将诸如Match.open.upcoming之类的范围链接起来。

What am I doing wrong here? 我在这里做错了什么? What's the correct way to do this? 正确的方法是什么? Any help would be appreciated. 任何帮助,将不胜感激。

Give this a shot - I've used something similar before and it seems to work for me: 试一试-我以前使用过类似的工具,它似乎对我有用:

class Match < ActiveRecord::Base
  has_and_belongs_to_many :users

  scope :open, joins(:matches_users)
               .select('matches.*')
               .group('matches.id')
               .having('count(matches_users.id) < 2')

...

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM