Rails类型BSON :: ObjectId的值不能写入Array类型的字段

时间:2017-02-01 17:11:00

标签: ruby-on-rails mongoid

Helo everyone,

当我运行任务时,我尝试使用rails和mongoid访问BSON ID,但是我有这样的错误消息:

// retrieve the custom control
IUIItem theCustomControl = window.Get(SearchCriteria.ByAutomationId("008"));

// get the childs items                
if(theCustomControl is CustomUIItem)
{
    // retrieve the custom control container
    IUIItemContainer foundCustomControl = (theCustomControl as CustomUIItem).AsContainer();

    // get the child components
    TextBox theEdit3 = foundCustomControl.Get<TextBox>("AutoSelectTextBox");
    Button increaseButton3 = foundCustomControl.Get<Button>("PART_IncreaseButton");
    Button decreaseButton3 = foundCustomControl.Get<Button>("PART_DecreaseButton");

    // perform actions...
    theEdit3.SetValue("800");
    increaseButton3.Click();
    increaseButton3.Click();
}

我不明白为什么,因为我只是输入一个id, 这是代码:

任务:

Mongoid::Errors::InvalidValue:
message:
  Value of type BSON::ObjectId cannot be written to a field of type Array
summary:
  Tried to set a value of type BSON::ObjectId to a field of type Array
resolution:
  Verify if the value to be set correspond to field definition

和模型中的字段:

namespace :geocodeschool do

  desc "Show premium school near non-premium school and update them"

  task :schgc => :environment do

      @schools = School.all

      def premium_school_aside(school)
        radius = 50
        @schools_a = School.near(school.coordinates.reverse, radius, units: :km)
        @schools_premium = @schools_a.premium_school.limit(3)
      end

      @schools.each do |school|
        premium_school_aside(school)
        puts "// -------------- //"
        puts "AUTO-ÉCOLE : #{school.title}"
        puts "// -------------- //"
        puts "les auto-écoles premiums près de #{school.title} : #{@schools_premium.count}"
        puts "-------"

        @schools_premium.each do |sa|
          puts sa.id
          school.update(school_premium_asides: sa.id)
        end

        puts "-------"

    end

  end

end

有人能解释我为什么,以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你的模型中有这个:

field :school_premium_asides, type: Array

所以当你分配给school_premium_asides时,Mongoid期望看到数组。但是在你的佣金任务中,你有:

school.update(school_premium_asides: sa.id)

并且可能sa.id是一个BSON::ObjectId值。这意味着您正在尝试将单个BSON::ObjectId写入Array类型的字段,这就是您的位置:

  

BSON :: ObjectId类型的值无法写入Array

类型的字段

错误来自。

我不确定您的代码尝试做什么,但我认为您希望将id的所有@schools_premium分配到school_premium_asides中的school字段}。如果是这样,那么你想要替换它:

@schools_premium.each do |sa|
    puts sa.id
    school.update(school_premium_asides: sa.id)
end

使用:

school.update(school_premium_asides: @schools_premium.map(&:id))