如何使用has_many:through保存数据

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

class Account  :destroy has_many :games, :through => :account_games end class Game  :destroy has_many :accounts, :through => :account_games end class AccountGame < ActiveRecord::Base belongs_to :account belongs_to :game end 

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

 @account = Account.new(params[:user]) @account.games << Game.first @account.save 

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

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

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

这应该工作:

 class AccountGame < ActiveRecord::Base belongs_to :account belongs_to :game attr_accessible :account_id, :game_id #<======= Notice this line end