存储计数属性的最佳方法是什么?

时间:2014-03-30 16:13:10

标签: ruby-on-rails ruby-on-rails-4

我正在尝试通过以下方式获取当前未处于有效匹配状态的所有用户:

User.where("id <> ? and active_matches = 0", user.id).limit(1).order("RANDOM()")

这样,每次用户创建匹配时,我都必须更新User实体的active_matches属性。我还有一个join_users连接表,我想知道我是否可以利用它来获取每个用户的活动匹配数量?

class Match < ActiveRecord::Base
before_destroy { users.clear } 

# Associations
has_and_belongs_to_many :users
belongs_to :user

class User < ActiveRecord::Base

# Associations
has_and_belongs_to_many :matches


class CreateMatches < ActiveRecord::Migration
  def change
    create_table :matches do |t|
      t.integer :user_1
      t.integer :user_2
      t.boolean :active
      t.integer :winner

      t.timestamps
    end
  end
end

class CreateMatchesUsers < ActiveRecord::Migration
  def change
    create_table :matches_users, :id => false do |t|
        t.integer :user_id
        t.integer :match_id

    end
  end
end


create_table "users", force: true do |t|
t.string   "email",                  default: "", null: false
t.string   "encrypted_password",     default: "", null: false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          default: 0,  null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "credit",                 default: 0
t.integer  "active_matches",         default: 0

1 个答案:

答案 0 :(得分:0)

关联范围怎么样?

class User
  has_many :active_matches, -> { where status: "active" }, class_name: "Match"
end

基本上,您会选择状态为活动的匹配项,因此您可以执行User.where(1).active_matches.count。您可能需要为HABTM(has_and_belongs_to_many)调整一些。我推荐has_many :through,但出于这个原因,请查看以下文章:http://blog.hasmanythrough.com/2006/2/28/association-goodness