How to save data with has_many :through

不想你离开。 提交于 2020-01-01 05:44:07

问题


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.


回答1:


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




回答2:


This should work:

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


来源:https://stackoverflow.com/questions/8404859/how-to-save-data-with-has-many-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!