小弟刚刚开始学 mongoid,基本照搬 activerecord 的写法,碰到 NoParent 错误,具体情况如下: 数据模型:
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
控制器全部用 scaffold 默认的样子
我创建了一个局部模板 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>
<% end %>
最后,在 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 console 进去查询这个库,却看到这些 img 都已经被创建,也跟 cargo 联系起来了,只是没有赋值,url 为空。 小弟很困惑,用 activerecord + mysql 的时候都是这么写的呀,不知道哪里没理解对,请师傅们点拨一下,谢谢。