如何保存的has_many数据:通过 [英] How to save data with has_many :through

查看:97
本文介绍了如何保存的has_many数据:通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多对许多喜欢下面的游戏和帐户模型之间的关系:

 类帐户<的ActiveRecord :: Base的
  的has_many:account_games,:依赖=> :破坏
  的has_many:游戏:通过=> :account_games
结束

一流的游戏和LT;的ActiveRecord :: Base的
  的has_many:account_games,:依赖=> :破坏
  的has_many:帐户,:通过=> :account_games
结束

类AccountGame<的ActiveRecord :: Base的
  belongs_to的:帐户
  belongs_to的:游戏
结束
 

现在我知道,让我们说,我想创建一个记录是这样的:

  @account = Account.new(PARAMS [:用户])
@ account.games<< Game.first
@ account.save
 

但我怎么更新一些AccountGame属性,而我这样做?让说 AccountGame 有一些外地名为分数,我将如何更新该属性?你能告诉我做到这一点的最好方法是什么?添加任何字段中通过表,而我保存对象。

解决方案

  @account = Account.new(PARAMS [:用户])
@accountgame = @ account.account_games.build(:游戏=> Game.first,:得分=→100)
@ accountgame.save
 

虽然我强烈建议,如果你开始添加列到你的加入模型,你把它叫做不同的东西,例如订阅或会员或类似的东西。一旦你添加列,它不再是一个联接模型,并开始只是作为一个普通的模型。

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.

这篇关于如何保存的has_many数据:通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆