在我的控制器中,我将两个不同实例变量的结果合并到一个实例变量中,并收到以下错误:
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
我怎样才能克服这个错误,或者获得以下结果的好方法是什么。
- 我想显示第一个对话兴趣类型,然后显示其他 17 种商业兴趣类型。
如果你想附加到一个数组,你有两个选择,在这里你必须注意你添加的内容:
# 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
,则可以看到这一点。
如果你想要一个嵌套数组:
@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]