关联和呈现来自多个模型的数据的正确方法是什么?
What's the correct way to associate & render data from multiple models?
我正在尝试编写一些 rails 代码,但我无法理解我需要的关联。
我到目前为止:
型号:
team.rb
has_many :rosters
roster.rb
belongs_to :team
has_many :riders
rider.rb
belongs_to :roster
控制器
团队_
controller.rb
def show
@team = Team.find([:params])
@rosters = @team.roster
end
@rosters
returns 以下(在 rails 控制台中):
<ActiveRecord::Associations::CollectionProxy [#<Roster id: 1, team_id: 1, created_at: "...", updated_at: "...", rider_id: 1>, #<Roster id: 2, team_id: 1, created_at: "...", updated_at: "...", rider_id: 2>]>
我的最终目标 是检索 rider_id
字段,并使用这些字段在我的 riders
table 中查找相关行。这就是我挣扎的地方。我不知道如何以允许我访问我需要的数据的方式关联我的模型。
此外,我已经阅读了有关 N+1 个查询 的信息,我觉得我已经在沿着这条路走下去了。我还担心我正在 teams_controller#show
上进行所有这些查询...我觉得它已经 做的太多了 .
如果我的问题需要更多代码来解释,我很乐意帮忙。感谢您的任何见解。
要使用您的关系查找关联的乘客:
def show
@team = Team.find(params[:id])
@roster = @team.roster
@riders = @roster.riders
end
就您的控制器所做的 'too much already' 而言,这仅取决于您要完成的任务。我觉得这个手柄还是比较瘦的
感谢@AytanLibowitz,我了解到我需要使用 has_many through:
协会。
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
我正在尝试编写一些 rails 代码,但我无法理解我需要的关联。
我到目前为止:
型号:
team.rb
has_many :rosters
roster.rb
belongs_to :team
has_many :riders
rider.rb
belongs_to :roster
控制器
团队_
controller.rb
def show
@team = Team.find([:params])
@rosters = @team.roster
end
@rosters
returns 以下(在 rails 控制台中):
<ActiveRecord::Associations::CollectionProxy [#<Roster id: 1, team_id: 1, created_at: "...", updated_at: "...", rider_id: 1>, #<Roster id: 2, team_id: 1, created_at: "...", updated_at: "...", rider_id: 2>]>
我的最终目标 是检索 rider_id
字段,并使用这些字段在我的 riders
table 中查找相关行。这就是我挣扎的地方。我不知道如何以允许我访问我需要的数据的方式关联我的模型。
此外,我已经阅读了有关 N+1 个查询 的信息,我觉得我已经在沿着这条路走下去了。我还担心我正在 teams_controller#show
上进行所有这些查询...我觉得它已经 做的太多了 .
如果我的问题需要更多代码来解释,我很乐意帮忙。感谢您的任何见解。
要使用您的关系查找关联的乘客:
def show
@team = Team.find(params[:id])
@roster = @team.roster
@riders = @roster.riders
end
就您的控制器所做的 'too much already' 而言,这仅取决于您要完成的任务。我觉得这个手柄还是比较瘦的
感谢@AytanLibowitz,我了解到我需要使用 has_many through:
协会。
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association