2010-11-25 7 views
0

Rails3、Mongoid、キュウリ。 user_idフィールドを設定できません:不正なObjectId形式

私はアカウントモデルを持っています:

class Account 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    referenced_in :user 
end 

class User 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    ... 

    references_one :account 

    ... 
end 

そして、次のようなシナリオを考えてみましょう:

 Scenario: Client views his account 
    Given the following accounts: 
     | user_id   | 
     | 1123322131  | 
     ..... 

そして次のステップ:

Given /^the following accounts:$/ do |class_name, table| 
    table.hashes.each do |attributes| 
    Account.create(attributes) 
    end 
end 

私はキュウリを実行しようとすると、常にエラーが発生します。

illegal ObjectId format (BSON::InvalidObjectId) 
./features/step_definitions/common_steps.rb:7:in `block (2 levels) in <top (required)>' 
./features/step_definitions/common_steps.rb:6:in `each' 
./features/step_definitions/common_steps.rb:6:in `/^the following accounts:$/' 
features/manage_accounts.feature:8:in `And the following accounts:' 

バックトレースのフルバージョン:https://gist.github.com/433ea982d876e1b1fa27

私は以下を使用します:Rails 3.0.3、Ruby 1.9.2、キュウリ1.9.4、機械技師2、モンゴイド。私のGemfile

どうしたのですか?

UPD。そうはっきりしない動作:

> a = Account.create :user_id => "123" 
BSON::InvalidObjectId: illegal ObjectId format 
> a = Account.create :user_id => 123 
=> #<Account _id: 4ceedf055e6f991aef000005, created_at: 2010-11-25 22:11:17 UTC, updated_at: 2010-11-25 22:11:17 UTC, user_id: 123> 
> a = Account.create :user_id => "4ceede9b5e6f991aef000007" 
=> #<Account _id: 4ceedf1b5e6f991aef000006, created_at: 2010-11-25 22:11:39 UTC, updated_at: 2010-11-25 22:11:39 UTC, user_id: BSON::ObjectId('4ceede9b5e6f991aef000007')> 

答えて

2

これはあなたの問題を解決することができます:

Given /^the following accounts:$/ do |class_name, table| 
    table.hashes.each do |attributes| 
    User.create(attributes).create_account 
    end 
end 

はあなたがUser用のカスタムの主キーを使用していますか? MongoidはBSON :: ObjectId( '4ceeaf282b2d3a2ab0000001')のような通常のBSON :: ObjectIdを期待しているようですが、1123322131のようなプレーンな文字列を渡しています。通常、レコードとその関連付けを作成しようとするときには注意が必要です。同じ時間

+0

解決策はこのようなIDを使用しています "4ceede9b5e6f991aef000007" – petRUShka

+0

あなたのユーザーを特定し、 – bowsersenior

+0

私はこの方法を理解しようとしました、それは素晴らしいでしょう、あなたが私を助けてくれれば:http://stackoverflow.com/questions/4281386/rails-キュウリ - 作る - オブジェクト - と - その - 協会 – petRUShka

関連する問題