2014-03-30 2 views
0

내가 의해 활성 일치하지 현재 모든 사용자를 가져 오기 위해 노력하고 있어요 :카운트 속성을 저장하는 가장 좋은 방법은 무엇입니까?

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

이 방법을, 나는 사용자가 일치하는 항목을 생성 할 때마다 내 사용자 개체의 active_matches 속성을 업데이트해야합니다. 나는 또한 조인 테이블 matches_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 

+0

모델과 결합 테이블의 관련 스키마 속성을 포함하여'User'와'Match' 사이의 관계에 대한 정보를 제공 할 수 있습니까? – tompave

+0

내 잘못, 업데이트 됨 – manis

답변

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.

관련 문제