Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save data with has_many :through

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.

like image 989
Eki Eqbal Avatar asked Dec 06 '11 18:12

Eki Eqbal


2 Answers

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

like image 144
Taryn East Avatar answered Sep 20 '22 16:09

Taryn East


This should work:

class AccountGame < ActiveRecord::Base
  belongs_to :account
  belongs_to :game
  attr_accessible :account_id, :game_id    #<======= Notice this line
end
like image 24
leoo.lai Avatar answered Sep 21 '22 16:09

leoo.lai