如何建立一种" belongs_to的:通过"没有建立直接的belongs_to的? [英] How to setup a kind of "belongs_to :through" without setting up a direct belongs_to?

查看:134
本文介绍了如何建立一种" belongs_to的:通过"没有建立直接的belongs_to的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道belongs_to的:通过是无效的,它只是我的尝试是我想达到的前preSS,只是和我一起承担了秒...

I know the "belongs_to :through" is not valid, its 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的:通过直接从players_controller'访问'division.name'没有'的队伍。 preFIX?我访问了很多'玩家'到'师'列,因此寻找一种方式来获得直接访问这些列。

So, is there a way to setup a "belongs_to :through" to access directly 'division.name' from 'players_controller' without the 'team.' prefix ?? I have to access a lot of columns from 'player' to 'division', so 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).

是否有可能做一个符号链接,例如'师',现在指的是team.division和联盟现指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.

BR, 乔纳斯

推荐答案

使用委托模型类。

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

  delegate :league, to: :division
end

参考:<一href="http://api.rubyonrails.org/classes/Module.html#method-i-delegate">http://api.rubyonrails.org/classes/Module.html#method-i-delegate

这篇关于如何建立一种&QUOT; belongs_to的:通过&QUOT;没有建立直接的belongs_to的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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