我有一個像下面遊戲和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
,我該如何更新這個屬性?你能告訴我有關最好的方法嗎?在保存對象時在通過表中添加任何字段。
將添加分數與遊戲,不知道這是明確的:'@ account.account_games.build(:遊戲=> Game.first,:得分=> 100) ' – Robin
是的,謝謝,對不起傻我忘了實際添加那一點。 –
非常感謝,很多人,讚賞,解決了我的問題 –