【问题标题】:Create a scope in rails based on HABTM association count根据 HABTM 关联计数在 Rails 中创建范围
【发布时间】:2014-03-03 22:21:31
【问题描述】:

我正在尝试根据模型的 HABTM 关联的计数创建一个 rails 范围,但我正在努力使用 SQL。

我希望 Match.open 返回少于两个用户的匹配项。我也有 Match.upcoming,它会在未来返回带有“future_date”的匹配项,效果很好。

我的代码:

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)
}

我目前收到错误:

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: 没有这样的列:matches_users.user_id: SELECT * FROM "matches" matches_users GROUP BY matches.id HAVING count(matches_users.user_id)

我目前正在使用类方法来实现这一点:

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

这行得通,但我真的很想把它移到一个范围内以提高速度,这样我就可以链接像 Match.open.upcoming 这样的范围。

我在这里做错了什么?这样做的正确方法是什么?任何帮助将不胜感激。

【问题讨论】:

  • 我的表matches_users的模式:create_table "matches_users", id: false, force: true do |t| t.integer "match_id" t.integer "user_id" 结束

标签: sql ruby-on-rails ruby


【解决方案1】:

试一试 - 我以前用过类似的东西,它似乎对我有用:

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

【讨论】:

  • 据我所知,这看起来不错,但我收到以下错误:ActiveRecord::ConfigurationError: Association named 'matches_users' was not found on Match;也许你拼错了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多