Ruby addtoset to a array field

时间:2016-04-07 10:36:06

标签: ruby-on-rails ruby ruby-on-rails-4 mongoid

When adding a value into a array field of a class, I am getting the error given below:

" Cannot apply $addToSet to a non-array field. Field named 'chat_user_ids' has a non-array type NULL in the document _id: ObjectId('5705fd637261695baa0f0000') ".

    class Wall
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::Timestamps::Updated
  include Geo
  include WallSearch
  include Common

  field :message,         type: String
  field :user_id,         type: BSON::ObjectId
  field :city,            type: String
  field :tag_id,          type: BSON::ObjectId
  field :group_id,        type: BSON::ObjectId
  field :tag_name,        type: String
  field :status,          type: Boolean, default: true
  field :abuse_count,     type: Integer, default: 0
  field :latitude,        type: String
  field :longitude,       type: String
  field :state,           type: String
  field :address,         type: String
  field :location,        type: Array
  field :chat_user_ids,   type: Array 

chat_user_ids is the array to which I am adding a value.

wall = Wall.where(_id: wall_id).first
    return false unless wall.present?
    wall.add_to_set(chat_user_ids: user_id)

1 个答案:

答案 0 :(得分:0)

user_id should rather be [user_id]

wall.add_to_set(chat_user_ids: [user_id])