Rails 将多个对象添加到空数组 [英] Rails adding multiple objects to an empty array

查看:34
本文介绍了Rails 将多个对象添加到空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个数组并向其中添加多个对象,但我不知道如何开始.请帮忙.

I'm trying to create an array and add multiple objects to it, but I wouldn't know how to start. Help please.

-- 编辑

这是我目前所拥有的.

@players = @user.players
@team = Team.all
@players.each do |player|
  @t = @team.find(player.team_id)
  @teams = Array.new
  @teams.push(@t)
end

推荐答案

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

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.

这篇关于Rails 将多个对象添加到空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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