5

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.

ardavis
  • 9,842
  • 12
  • 58
  • 112
Eki Eqbal
  • 5,779
  • 9
  • 47
  • 81

2 Answers2

13
@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.

Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • You would add the score with the game, not sure it's clear: `@account.account_games.build(:game => Game.first, :score => 100)` – Robin Dec 06 '11 at 21:47
  • yes, thanks, sorry silly me I forgot to actually add that bit. – Taryn East Dec 06 '11 at 21:49
  • What Robin mentions is a work-around, but does not answer the OPs original question. *How to do you update some of the attributes in the join-model during "Account.account_games.create()"* – Tilo Feb 16 '12 at 07:58
  • Yes, good point. You could do this by using `accepts_nested_attributes_for` there are lots of questions on S/O about the use of this, stick it in the searchbar and have a looksee :) – Taryn East Feb 20 '12 at 22:45
  • I agree with @Taryn East, renaming the join table is necessary. Using the Rails join table conventional naming used for many_to_many associations can cause issues when using has_many through – Mark Kenny Apr 05 '19 at 14:12
2

This should work:

class AccountGame < ActiveRecord::Base
  belongs_to :account
  belongs_to :game
  attr_accessible :account_id, :game_id    #<======= Notice this line
end
Samiron
  • 5,169
  • 2
  • 28
  • 55
leoo.lai
  • 29
  • 1