2014-03-30 2 views
0

automatch 시스템을 만들려고하지만 아래 코드는 "matches"테이블에만 삽입합니다. matches_users 조인 테이블에 두 플레이어 ID를 모두 삽입하고 싶습니다.이를 수정하는 방법은 무엇입니까? 감사! 클래스의 여러 인스턴스에 대한 조인 테이블 업데이트

class Match < ActiveRecord::Base 

# Associations 
has_and_belongs_to_many :users 
belongs_to :user 

def initialize_match 
    return false unless empty? 
    players = match_players 
    with_lock do 
     # Makes transaction 
     self.user_1 = players[0].id 
     self.user_2 = players[1].id 
     finished = false 
     save! 
    end  
end 

def match_players 
    users = User.limit(2).order("RANDOM()") 
end 

그리고 내 사용자 클래스

class User < ActiveRecord::Base 
devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

# Associations 
has_and_belongs_to_many :matches 
+0

는 당신이'belongs_to 제거 할 필요가 있다고 생각 :이 – emaillenin

답변

1

당신이 users 속성을 지정하지 않았기 때문에 협회 저장되지 않습니다. , 일치하는 항목을 삭제 :dependent 속성을 사용할 때

with_lock do 
     # Makes transaction 
     self.user_1 = players[0].id # Remove this if user_1 is not an attribute of Match 
     self.user_2 = players[1].id # Remove this if user_2 is not an attribute of Match 
     users = [] 
     users << User.find(players[0].id)) 
     users << User.find(players[1].id)) 
     self.users = users 
     finished = false 
     save! 
end  

은 (조인 테이블)에 사용자 데이터를 삭제합니다.

class Match < ActiveRecord::Base 

    # use this if you using has_many :through 
    # In this method, you should use Match.destroy(id) instead of Match.delete(id) 

    has_many :users, through: :MatchUsers, :dependent => :destroy 

    # use this if you are using has_and_belongs_to_many 

    has_and_belongs_to_many :users 
    before_destroy { users.clear } 

docs :

4.3.2.4 :dependent

Controls what happens to the associated objects when their owner is destroyed:

:destroy causes all the associated objects to also be destroyed

:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute) :nullify causes the foreign keys to be set to NULL. Callbacks are not executed.

:restrict_with_exception causes an exception to be raised if there are any associated records

:restrict_with_error causes an error to be added to the owner if there are any associated objects

+0

완벽한에서 – manis

+0

마르크을 user' 오 또 다른 한가지, 나는 일치를 호출 할 때 .delete.all, Match 테이블의 항목 만 삭제됩니다.이 또한 join 테이블의 항목을 포함하도록 확장합니까? – emaillenin

+0

작동하는 경우 정답으로 감사 일치 클래스 – manis

관련 문제