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

blabber · 2014年03月14日 · 最后由 blabber 回复于 2014年03月15日 · 3713 次阅读

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

共收到 3 条回复

@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了。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册