1

在我的控制器中,我将两个不同实例变量的结果合并到一个实例变量中,但出现以下错误:

undefined method `<<' for nil:NilClass

这是我的控制器代码

  @conversational = InterestType.where("institution_id = ? or global = ? and category_id = ?", current_user.profile.institution_id, true, 1).first

    @commercial = InterestType.where("institution_id = ? or global = ? and category_id = ?", current_user.profile.institution_id, true, 2).limit(17)

    @user_interest_types << @conversational

    @user_interest_types << @commercial

我怎样才能克服这个错误或者什么是获得以下结果的好方法。

  1. 我想先显示对话兴趣类型,然后再显示其他 17 种商业兴趣类型。
4

2 回答 2

4

如果你想追加到一个数组,你有两个选择,在这里你必须注意你要添加的内容:

# Define an empty array
@user_interest_types = [ ]

# Add a single element to an array
@user_interest_types << @conversational

# Append an array to an array
@user_interest_types += @commercial

如果您同时使用<<这两种操作,您最终会将一个数组推一个数组,并且生成的结构具有多个层。如果您调用inspect结果,您可以看到这一点。

于 2012-06-28T14:07:19.923 回答
0

如果你想要一个嵌套数组:

@user_interest_types = [@conversational, @commercial]

# gives [it1, [it2, it3, it4]]

或者,如果您更喜欢平面阵列:

@user_interest_types = [@conversational, *@commercial]

# gives [it1, it2, it3, it4]

假设@conversational = it1@commercial = [it2, it3, it4]

于 2012-06-28T14:13:17.000 回答