2017-02-01 10 views
0

のHELOみんなのフィールドに書き込むことができない私は、タスクを実行すると、レールとmongoidでBSON同上にアクセスしようとするが、私はこのエラーを持っていますメッセージ:RailsのタイプBSONの値::のObjectIdが</p> <p>、型アレイ

タスク:

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 
0私は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 

私は、理由を理解していない、ここで はコードです

と、モデル内のフィールド:

field :school_premium_asides, type: Array 

誰かが私に理由を説明することができず、この問題を解決する方法?

答えて

0

あなたのモデルでこれを持っている:

field :school_premium_asides, type: Array 

のでMongoidはあなたがschool_premium_asidesに割り当てるときの配列を見て期待しています。しかし、その後、あなたの熊手にあなたが持っているタスク:

school.update(school_premium_asides: sa.id) 

と、おそらくsa.idは、単一BSON::ObjectId値です。それはあなたがArray型のフィールドに単一BSON::ObjectIdを書くしようとしていることを意味し、それがだどこ:タイプBSONの

値::のObjectIdは、Array型のフィールドに書き込むことができません

エラーが発生します。

私はあなたのコードがやろうとしているものかどうか分からないが、私はあなたがschoolschool_premium_asidesフィールドに@schools_premiumのすべてid Sを割り当てたいと思います。

@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)) 
+0

あなたの答えをありがとう!私はあなたがしたいことを理解していると思いますが、3つの最も近いプレミアムスクールをArrayに配置して、それらを表示する必要があります。そのため、3つのIDを使用して配列を作成する理由は、 ? –

+0

あなたはちょうど3つの最も近いものを見つけ、 'school.update(school_premium_asides:those_three_ids_in_an_array)'を見つけなければなりません。 –

+0

しかし私はこのコードを持っています: '@schools_premium.each do | sa | puts sa.id school.update(school_premium_asides:sa.id) end'それはうまくいくはずですか? –

関連する問題