【问题标题】:Mongoid Create New Embedded Document Inside ParentMongoid 在父级中创建新的嵌入文档
【发布时间】:2012-09-28 08:49:06
【问题描述】:

我有两个模型正在处理事件和报告。报告并嵌入事件中。我在为特定事件创建新报告时遇到问题。

我认为我的报表控制器新操作需要如下所示:

@event = Event.find(params[:eventid])
@report = @event.report.build

在我的事件模型中,我有以下设置:

embeds_one :report
accepts_nested_attributes_for :report

当我尝试保存时收到以下错误:

Mongoid::Errors::NoParent

这是我的报告模型

class Report
include Mongoid::Document
include Mongoid::Timestamps
field :test, type: String
embedded_in :event, :inverse_of => :report
embeds_many :report_details
accepts_nested_attributes_for :report_details,
  :allow_destroy => true, 
    :reject_if => proc { |attributes| 
      attributes['name'].blank? && attributes['_destroy'].blank? 
    }

这是我的事件模型

class Event
include Mongoid::Document
include Mongoid::Timestamps
embeds_one :report
accepts_nested_attributes_for :report,
:allow_destroy => true, 
  :reject_if => proc { |attributes| 
    attributes['name'].blank? && attributes['_destroy'].blank? 
  }

提前致谢。

【问题讨论】:

  • 请给出你的模型结构

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

确保在创建新报告时在其上设置event_id

您可以按照您的提示使用 @report = @event.report.build(params[:report]) 或确保在 params 哈希中包含“event_id”来完成此操作。

【讨论】:

  • 没问题!如果这样可以解决问题,您介意接受答案吗?
猜你喜欢
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多