繁体   English   中英

未定义的方法`<<'表示nil:NilClass在合并实例变量时出现此错误

[英]undefined method `<<' for nil:NilClass got this error while merging instance variables

在我的控制器中,我将两个不同的实例变量的结果合并为一个实例变量,我得到一个跟随错误:

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种商业兴趣类型。

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

# 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM