38

我有一个现有用户,它有一个序列化字段,我希望能够将最近的消息添加到数组/序列化字段。

class User < ActiveRecord::Base
 serialize :recent_messages
end

在我试过的控制器中

@user = current_user
@user.recent_messages << params[:message]
@user.save

但我收到以下错误:

NoMethodError (undefined method `<<' for nil:NilClass):

在我的架构中,我有:

create_table "users", :force => true do |t|
    t.text     "recent_messages"
  end

关于我哪里出错的任何想法?

4

3 回答 3

62

You can pass a class to serialize:

class User < ActiveRecord::Base
  serialize :recent_messages, Array
end

The above ensures that recent_messages is an Array:

User.new
#=> #<User id: nil, recent_messages: [], created_at: nil, updated_at: nil>

Note that you might have to convert existing fields if the types don't match.

于 2013-10-02T10:25:11.543 回答
2

这是因为当您第一次尝试将项目推送到您的recent_messages时,没有将项目推送到的数组(该字段nil默认为)。因此,您必须先创建数组,然后才能推送到它

@user = current_user
if @user.recent_messages.nil?
  @user.recent_messages = [params[:message]]
else
  @user.recent_messages << params[:message]
end
@user.save
于 2013-10-02T10:06:05.260 回答
2

You can also try following code:- By default @user.recent_messages would be nil

@user.recent_messages ||= []
@user.recent_messages << params[:message]
@user.save
于 2013-10-02T10:10:16.467 回答