ruby-on-rails - 未定义方法 `<<' 为 nil :NilClass got this error while merging instance variables

标签 ruby-on-rails ruby

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

undefined method `<<' for nil:NilClass

这是我的 Controller 代码

  @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. 我想先显示 session 兴趣类型,然后再显示其他 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就可以看到这个关于结果。

关于ruby-on-rails - 未定义方法 `<<' 为 nil :NilClass got this error while merging instance variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246356/

相关文章:

ruby-on-rails - 在 Rails 中更新数据库中的多行,每行都具有唯一值

ruby-on-rails - 我可以强制执行事件记录查询链吗?

ruby-on-rails - 用整数写一个 Rails 验证器

ruby - 如何使用puppet在服务器上设置环境变量?

ruby-on-rails - 如何检查模型的 before_save 回调中的修改值?

ruby gem 安装

ruby-on-rails - 从 CanCan 的 Rails 3.0.9 升级到 Rails 3.1 错误

javascript - 如何集成jquery.fileupload-rails?

javascript - 找不到 javascript 库的 ruby​​-toolbox 等价物

regex - 匹配字符串中的 url 路径和 IP 地址