User
has_many :pin_boards
has_many :pins, through: :pin_boards, source: :players
PinBoard
belongs_to :user
has_many :pin_board_player_assignments
has_many :players, through: :pin_board_player_assignments
PinBoardPlayerAssignment
belongs_to :pin_board
belongs_to :player
Player
has_many :pin_board_player_assignments
has_many :pin_boards, through: :pin_board_player_assignments
因此,基本上,您需要添加另一个名为PinBoardPlayerAssignment
. 从那里,我强烈建议使用此连接模型来创建和管理分配,如下所示:
PinBoardPlayerAssignment
def self.create_between(a_pin_board, a_player)
assignment = a_pin_board.pin_board_player_assignments.build
assignment.player = a_player
assignment.save!
end
这样,您可以使用 onPinBoard
或on的实例方法Player
来 DRYly 创建 PinBoard 和 Player 之间的分配。基本上,让最了解 pin_boards 和玩家的对象成为管理它们之间关系的对象。
PinBoard
def add_player(a_player)
PinBoardPlayerAssignment.create_between(self, a_player)
end
Player
def add_to_pin_board(a_pin_board)
PinBoardPlayerAssignment.create_between(a_pin_board, self)
end
最棒的是 Rails 3.2+ 允许嵌套 :through 关系,因此您的原始请求@user.pins
应该编译通过 pin_board 然后通过 pin_board_player_assignment 表的结果。