2012-06-28 21 views
1

在我的控制器我正在合并两个不同的实例变量的结果为一个实例变量得到这个错误,并收到以下错误:未定义的方法`<<”的零:NilClass而合并实例变量

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个商业兴趣类型。
+3

'@ user_interest_types'必须是'nil'。在将对象推到它上面之前,请检查并确保已初始化它。 –

+0

@user_interest_types = {}是这样的吗? – chaitanya

+1

不,'@user_interest_types = []' – Mischa

回答

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的结果。

+0

hi @tadman,感谢您的解释 – chaitanya

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]

相关问题