MongoDB Mongoid 环境下给局部模板传参数的写法问题

blabber · March 14, 2014 · Last by blabber replied at March 15, 2014 · 7793 hits

小弟刚刚开始学 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 的时候都是这么写的呀,不知道哪里没理解对,请师傅们点拨一下,谢谢。

@Rei @huacnlee @ashchan @hisea 几位大大们,不知能否解惑?谢谢!

img 是 embedded document,mongoid 是不允许直接创建 embedded document 的。或者不用 embeds_many 而改用 has_many;或者创建 Cargo+Img,而不是单独创建 Img

确实是,embedded document 里面用 formfor(img) 没有意义。改成 has_many,再把 cargo_id 加到 img 里面就 ok 了。

You need to Sign in before reply, if you don't have an account, please Sign up first.