rails和mongomapper一个关系:创建新条目

时间:2012-08-27 22:55:32

标签: ruby-on-rails mongomapper relation

我用mongomapper创建简单的rails应用程序来做一些清单:基本上,我希望能够定义替换单元应该是什么。

所以我有模特:

class Replacement
  include MongoMapper::Document
  set_collection_name 'asset_replacements'
  key :device, String
  one :current, :class_name => 'Asset'
  one :replacement, :class_name => 'Asset'
end

class Asset
  include MongoMapper::Document
  set_collection_name 'assets__collection'
  key :_id, Mongo:ObjectId
  key :vendor, String
  key :model, String
end

我有一个form.erb:

<%= form_for(@replacement) do |f| %>
  <div class="field">
    <%= f.label :device %><br />
    <%= f.text_field :device %>
  </div>
  <div class="field">      
    <%= f.label :current_id %><br />
    <%= f.collection_select :current, Asset.sort(:model), :id, :model %>
  </div>
  <div class="field">      
    <%= f.label :replacement_id %><br />
    <%= f.collection_select :replacement, Asset.sort(:model), :id, :model %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

,控制器是:

def create
  p = params[:replacement]
  @replacement = Replacement.new( p )

  respond_to do |format|
    if @replacement.save
      format.html { redirect_to @replacement, notice: 'Replacement was successfully created.' }
      format.json { render json: @replacement, status: :created, location: @replacement }
    else
      format.html { render action: "new" }
      format.json { render json: @replacement.errors, status: :unprocessable_entity }
    end
  end
end

问题是,当我在rails app上创建新的Replacement时,我收到以下错误:

NoMethodError in ReplacementsController#create
  undefined method `each_pair' for "50381cb24ed00a707c0000c1":String

我似乎很难将replacementcurrent的字符串与可用的mongo对象匹配。

我尝试使用Asset.find( BSON::ObjectId.from_string( p['current'] )进行查找,这不会引发错误,但似乎也没有将关系放入mongo集合中。

我做错了什么?

0 个答案:

没有答案