新手问题 问一个关联的问题

zix · 2016年10月05日 · 最后由 angelfan 回复于 2016年10月07日 · 2250 次阅读

三个 models :Game,Player,Hint 每个 Game 有若干 Player,同时有若干 Hint, 每个 Player 可以又一个 Hint 或者没有

我现在是这样写的

class Game < ApplicationRecord
  has_many :players, dependent: :destroy, inverse_of: :game
  accepts_nested_attributes_for :players

  has_many :hints, through: :players, dependent: :destroy
  accepts_nested_attributes_for :hints

class Player < ApplicationRecord
  belongs_to :game, inverse_of: :players
  has_one :hint
class Hint < ApplicationRecord
  belongs_to :player
end

但是这样有个问题

@game.hints.create!(Lv:1,content:"房间#{i}不是出口")

的时候,会报错:

Validation failed: Player must exist

因为每个 Hint 可以属于某个 Player 也可以不属于,所以我又不能用:

player.hints.create

正确应该如何表述它们的关系呢?

三个 models :Game,Player,Hint 每个 Game 有若干 Player,同时有若干 Hint,每个 Player 可以又一个 Hint 或者没有

Game: has many players, hints

Player: has one hint

根据你的描述,不需要用到中间表才对吧,through 是多余的

#1 楼 @Catherine belong to 怎么写?

直接 belongs_to :game 就可以了,对应数据库,players 表建立 game_id 字段

如#3 所说,直接 belongs_to 就可以了。

而且 through 的用法不是楼主想的那样用的,参考http://guides.ruby-china.org/association_basics.html#has_many-:through-%E5%85%B3%E8%81%94

每个 Game 有若干 Player,同时有若干 Hint,每个 Player 可以又一个 Hint 或者没有

既然如此,为何不分成两种:

@game.hints.create
@game.player.hints.create

因为每个 Hint 可以属于某个 Player 也可以不属于

所以你不能这样写

has_many :hints, through: :players

可以

class Hint < ApplicationRecord
  belongs_to :player
  belongs_to :game
end
zix 关闭了讨论。 10月07日 17:51
需要 登录 后方可回复, 如果你还没有账号请 注册新账号