Ruby on rails Rails3,Mongoid,黄瓜。Can';设置用户id字段:ObjectId格式非法

Ruby on rails Rails3,Mongoid,黄瓜。Can';设置用户id字段:ObjectId格式非法,ruby-on-rails,cucumber,mongoid,Ruby On Rails,Cucumber,Mongoid,我有一个帐户模型: class Account include Mongoid::Document include Mongoid::Timestamps referenced_in :user end 和用户: class User include Mongoid::Document include Mongoid::Timestamps ... references_one :account ... end 下面的场景(我尝试将引用设置为一个关

我有一个帐户模型:

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

  referenced_in   :user
end
和用户:

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

  ...

  references_one :account

  ...
end
下面的场景(我尝试将引用设置为一个关联):

以及以下步骤:

Given /^the following accounts:$/ do |class_name, table|
  table.hashes.each do |attributes|
    Account.create(attributes)
  end
end
当我尝试运行cucumber时,总是会出现错误:

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:'
非法的ObjectId格式(BSON::InvalidObjectId) ./features/step_definitions/common_steps.rb:7:in“block(2层)in” /功能/步骤定义/常用步骤。rb:6:“每个”中 ./features/step\u definitions/common\u steps.rb:6:in`/^以下帐户:$/' 功能/管理账户。功能:8:in`和以下账户:' 回溯的完整版本:

我使用:Rails 3.0.3、Ruby 1.9.2、cucumber 1.9.4、machinist 2、mongoid。我的

我做错了什么

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')>
>a=Account.create:user\u id=>“123”
BSON::InvalidObjectId:ObjectId格式非法
>a=Account.create:user\u id=>123
=> #
>a=Account.create:user_id=>“4ceede9b5e6f991aef000007”
=> #

这可以解决您的问题:

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

您是否为用户使用自定义主键?Mongoid似乎期望像BSON::ObjectId('4ceeaf282b2d3a2ab0000001'这样的普通BSON::ObjectId,但您传递的是一个像1123322131这样的普通字符串。通常,在尝试同时创建记录及其关联时必须小心

是的,您是对的。请参阅UPD。解决方案是使用这样的ID“4ceede9b5e6f991aef000007”我建议您在cucumber规范中使用另一个字段,如
用户名
电子邮件
,以识别您的用户,并让Mongoid为您创建对象ID。它更可靠,cucumber规范更易读。我试图理解这种方式,如果您能帮助我:
Given /^the following accounts:$/ do |class_name, table|
  table.hashes.each do |attributes|
    User.create(attributes).create_account
  end
end