2011-12-06 37 views
3

我有一個像下面遊戲和Account模型之間的許多一對多的關係:如何使用的has_many保存數據:通過

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 

現在我知道,讓我們說,我想創建一個記錄是這樣的:

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

但是我該如何更新AccountGame中的某些屬性?可以說AccountGame有一些字段叫做score,我該如何更新這個屬性?你能告訴我有關最好的方法嗎?在保存對象時在通過表中添加任何字段。

回答

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

雖然我強烈建議如果你開始向你的連接模型添加列,你稱之爲不同的例如「訂閱」或「會員」或類似的東西。一旦你添加了列,它就不再是一個連接模型,而只是一個常規模型。

+0

將添加分數與遊戲,不知道這是明確的:'@ account.account_games.build(:遊戲=> Game.first,:得分=> 100) ' – Robin

+0

是的,謝謝,對不起傻我忘了實際添加那一點。 –

+0

非常感謝,很多人,讚賞,解決了我的問題 –

2

這應該工作:

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