How do I set up a kind of “belongs_to :through” association without a direct belongs_to?

╄→尐↘猪︶ㄣ 提交于 2019-12-17 15:53:30

问题


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...

This is what I have:

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

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.

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).

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.


回答1:


Use delegate in the model class.

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

  delegate :league, to: :division
end

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




回答2:


You may try

    class Player
      belongs_to :team
      has_one :division, :through => :team
    end



回答3:


You can define a helper method in your player model:

def division
  team.division
end

def league
  team.division.league
end

Of course, this only relates to readability of your code and does not affect the form of the database queries involved. If your statement generates multiple SQL queries but you want only one, check out the .include option here: Rails Guides - Active Record Query Interface



来源:https://stackoverflow.com/questions/7834073/how-do-i-set-up-a-kind-of-belongs-to-through-association-without-a-direct-bel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!