本文介绍了如何设置一种“ belongs_to:through”协会没有直接的belongs_to?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 belongs_to:through无效。这只是我表达自己想要实现的目标的尝试。只需忍受我几秒钟...

I know that "belongs_to :through" is not valid. It's just my attempt to express what I want to achieve. Just bear with me for a sec...

这就是我所拥有的:

class League
  has_many :divisions
end

class Division
  belongs_to :league
  has_many :teams
end

class Team
  belongs_to :division
  has_many :players
end

class Player
  belongs_to :team
end

现在,要制作棒球卡视图表格,我需要:

Now, in order to make a "baseball card" view form, I need:

name
team.name
team.division.name
team.division.league.name

因此,有没有办法建立 belongs_to:through关联以直接访问 division.name来自 players_controller,不带 team。前缀?我必须访问从玩家到分区的许多列,因此我正在寻找一种直接访问这些列的方法。

So, is there a way to set up a "belongs_to :through" association to directly access 'division.name' from 'players_controller' without the 'team.' prefix?? I have to access a lot of columns from 'player' to 'division', so I'm looking for a way to get "direct" access to those columns.

一种选择是在玩家表中包括 division_id列,但有人告诉我这将破坏关系数据模型,因为如果数据选择功能处理不当,它将导致不一致。玩家A在A部门的团队A上,但玩家A的 division_id列设置为B部门。

One option is to include a 'division_id' column in the 'players' table, but I've been told that it would kinda break the relational data model, since it would allow for inconsistency if the data selection functionality is not properly handled (e.g. player A is on team A which is in division A, but player A has its division_id column set to division B).

是否可以建立符号链接 ,例如'division'现在是指'team.division','league'现在是指'team.division.league'??

Is it possible to make a "symbolic link", e.g. 'division' now refers to 'team.division', and 'league' now refers to 'team.division.league'??

或者,是唯一的真实选择每次都使用完整路径?

Or, is the only true option to use the full path each time??

希望有人可以提供帮助。

Hope someone can help.

推荐答案

在模型类中使用委托。

class Team < ActiveRecord::Base
  belongs_to :division
  has_many :players

  delegate :league, to: :division
end

参考:

这篇关于如何设置一种“ belongs_to:through”协会没有直接的belongs_to?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:32