如何使用has_many保存数据:通过

Eki*_*bal 5 ruby activerecord ruby-on-rails ruby-on-rails-3

我在游戏和帐户模型之间有多对多的关系,如下所示:

class Account < ActiveRecord::Base
  has_many :account_games, :dependent => :destroy
  has_many :games, :through => :account_games
end

class Game < ActiveRecord::Base
  has_many :account_games, :dependent => :destroy
  has_many :accounts, :through => :account_games
end

class AccountGame < ActiveRecord::Base
  belongs_to :account
  belongs_to :game
end
Run Code Online (Sandbox Code Playgroud)

现在我知道让我们说我要创建一个类似的记录:

@account = Account.new(params[:user])
@account.games << Game.first
@account.save
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我应该如何更新AccountGame中的一些属性?假设AccountGame有一些字段叫做score,我该如何更新这个属性?你能告诉我最好的方法吗?在我保存对象时,在直通表中添加任何字段.

Tar*_*ast 12

@account = Account.new(params[:user])
@accountgame = @account.account_games.build(:game => Game.first, :score => 100)
@accountgame.save
Run Code Online (Sandbox Code Playgroud)

虽然我强烈建议如果你开始在连接模型中添加列,你称之为不同的列,例如"订阅"或"成员资格"或类似的东西.添加列后,它将停止作为连接模型,并开始只是一个常规模型.