使用mongoid在mongodb中创建嵌入文档时,Mongoid :: Errors :: NoParent

时间:2014-03-14 06:44:34

标签: ruby-on-rails mongodb mongoid

我正在学习MongoId。测试1-n嵌入文档时,我收到了“无父错误”。 以下是模型:

class Cargo
   include Mongoid::Document
  field :name, type: String
  field :description, type: String
  field :price, type: Float
  embeds_many :imgs
 end
class Img
  include Mongoid::Document
  field :url, type:String
  embedded_in  :cargo
end

所有控制器都作为脚手架默认设置。

为img。

创建了部分模板imgs / _formofmg.html.erb
<%= form_for(img) do |f| %>
    <% if img.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(img.errors.count, "error") %> prohibited this img from being saved:</h2>

          <ul>
            <% img.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
    <% end %>

<div class="field">
  <%= f.label :url %><br>
  <%= f.text_field :url%>
</div>

<div class="actions">
  <%= f.submit %>
</div>

在cargos / show.html.erb中,我渲染了这个模板:

<%= render :partial => "imgs/formofimg",:locals => {:img=> @cargo.imgs.build()} %>

提交此模板以创建嵌入Cargo的img时,抛出错误:

Mongoid::Errors::NoParent in ImgsController#create
Problem: Cannot persist embedded document Img without a parent document. Summary: If the document is embedded, in order to be persisted it must always have a reference to its parent document. This is most likely caused by either calling Img.create or Img.create! without setting the parent document as an attribute. Resolution: Ensure that you've set the parent relation if instantiating the embedded document direcly, or always create new embedded documents via the parent relation.

Extracted source (around line #30):

respond_to do |format|
if @img.save
format.html { redirect_to @img, notice: 'Img was successfully created.' }
format.json { render action: 'show', status: :created, location: @img }
else

Rails.root: /home/fwoods/dev/prj/mongoid_spec
Application Trace | Framework Trace | Full Trace

app/controllers/imgs_controller.rb:30:in `block in create'
app/controllers/imgs_controller.rb:29:in `create'

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"HKTX33u28NrChiUJ02O+yCnbJOA1IFuSPQphCAPT4LA=",
 "img"=>{"url"=>"qweqwe"},
 "commit"=>"Create Img"}

但是当我在rails控制台中检查数据库时,所有imgs都是使用空url属性创建的。

irb(main):009:0> Cargo.first().imgs
D, [2014-03-09T16:31:29.014384 #10070] DEBUG -- :   MOPED: 127.0.0.1:27017 QUERY        database=mongoid_spec_development collection=cargos selector={"$query"=>{}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil runtime: 0.8659ms
=> [#<Img _id: 5319d7f97562751fab020000, url: nil>, #<Img _id: 5319dac77562751fab030000, url: nil>, #<Img _id: 5319dbc57562751fab040000, url: nil>, #<Img _id: 5319dce07562751fab050000, url: nil>, #<Img _id: 5319dd0e7562751fab060000, url: nil>, #<Img _id: 5319dd277562751fab070000, url: nil>, #<Img _id: 531c26aa7562752756000000, url: "example">]

注意到最后一个img“example”是由irb创建的,而不是Web应用程序。

渲染部分模板时参数设置是否错误?

0 个答案:

没有答案