更新多个类实例的连接表

时间:2014-03-30 11:59:27

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

我正在尝试制作一个自动匹配系统,但下面的代码只会将它们插入“匹配”表中。我希望它将两个玩家ID都插入到matches_users连接表中,如何更正?谢谢!

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

1 个答案:

答案 0 :(得分:1)

由于您尚未分配users属性,因此未保存关联。

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    

要删除用户数据(在联接表中),删除匹配时,请使用:dependent属性。

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:依赖

     

控制关联对象在其所有者身份时会发生什么   破坏:

     

:destroy导致所有相关对象也被销毁

     

:delete_all导致所有关联对象直接从数据库中删除(因此不会执行回调):nullify导致外键设置为NULL。回调不会被执行。

     

:如果存在任何关联记录,则restrict_with_exception会引发异常

     

:如果存在任何关联对象,则restrict_with_error会将错误添加到所有者