I have many-to-many relationship between Game and Account models like below:
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
Now I know let's say I want to create a record something like:
@account = Account.new(params[:user])
@account.games << Game.first
@account.save
But how am I supposed to update some of the attributes in AccountGame while I'm doing that? Lets say that AccountGame
has some field called score
, how would I update this attribute? Can you tell me about the best way to do that? To add any field in the through table while I'm saving the object.
@account = Account.new(params[:user])
@accountgame = @account.account_games.build(:game => Game.first, :score => 100)
@accountgame.save
Though I'd strongly recommend that if you start adding columns to your join-model that you call it something different eg "subscription" or "membership" or something similar. Once you add columns it stops being a join model and starts just being a regular model.
This should work:
class AccountGame < ActiveRecord::Base
belongs_to :account
belongs_to :game
attr_accessible :account_id, :game_id #<======= Notice this line
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With