且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 将多个对象添加到空数组

更新时间:2023-12-01 21:44:46

您的代码片段中发生了很多事情,使其无法正常工作(或者至少是不必要的).您不应该在循环的每次迭代中创建一个新数组.类似的东西应该会好得多:

There's a lot going on in your code snippet that is making it not work (or at the very least is unnecessary). You shouldn't be creating a new array in every iteration of your loop. Something along the lines of this should be much better:

@players = @user.players
@teams = Array.new
@players.each do |player|
  @teams << Team.find(player.team_id)
end

这将解决您最初的问题,但这肯定不是解决您正在尝试做的事情的***方式.将以下内容添加到您的 PlayerUser 模型:

This will solve your original problem, but it's certainly not the best way of going about what you're trying to do. Add the following to your Player and User models:

class Player < ActiveRecord::Base
  belongs_to :team
end

class User < ActiveRecord::Base
  has_many :players
  has_many :teams, through: :players
end

然后,为了获得您正在寻找的团队,您可以将代码简化为以下内容:

Then, in order to get the teams you're looking for, you can simplify your code to the following:

@teams = @user.teams

您应该尝试阅读文档,而不仅仅是 ruby 数组,还有 Active Record Associations 的 Rails 指南.此外,将来请先尝试发布代码片段,以便为您的问题提供更多背景信息.

You should try going through the documentation not only for ruby arrays, but also the Rails guide for Active Record Associations. Also, in the future try posting the snippet of code first, in order to provide more context to your issue.