我如何设置一种“belongs_to :through"?没有直接belongs_to 的关联? [英] How do I set up a kind of "belongs_to :through" association without a direct belongs_to?

查看:29
本文介绍了我如何设置一种“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"关联来直接从players_controller"访问division.name"而无需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.

一种选择是在 'players' 表中包含一个 '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??

希望有人能帮忙.

推荐答案

在模型类中使用委托.

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

  delegate :league, to: :division
end

参考:http://api.rubyonrails.org/classes/Module.html#method-i-delegate

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

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