从父mongoid中删除嵌入的成员

时间:2012-10-04 06:28:04

标签: ruby-on-rails-3 mongodb mongoid embed nested-attributes

我有以下型号:

class User
  include Mongoid::Document
  embeds_many :user_missions
  attr_accessible :user_missions_attributes
  accepts_nested_attributes_for :user_missions, :allow_destroy => true
end

class UserMission
  include Mongoid::Document

  embedded_in :user, :inverse_of => :user_missions

  belongs_to :mission, :inverse_of => nil
  validates_presence_of :mission, :inverse_of => nil

  attr_accessible :mission_title

  def mission_title
    mission.try(:title)
  end

  def mission_title=(title)
    self.mission = Mission.find_or_create_by(:title => title) if title.present?
  end
end

class Mission
  include Mongoid::Document

  attr_accessible :title
  field :title, type: String
  validates_presence_of :title
end

问题是我在从用户删除user_mission时遇到问题。

我的观点失败了(基本上是从railscasts逐字逐句):

jQuery ->
  $('form').on 'click', '.remove_fields', (event) ->
    $(this).prev('input[type=hidden]').val('1')
    $(this).closest('fieldset').hide()
    event.preventDefault()

<fieldset>
  <%= f.object.mission.title %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

我似乎在以下规范中遇到了问题

it "should delete using nested attributes" do
  user = User.create(:username => "username", :email => "user@example.com", :password => "password", :password_confirmation => "password")
  user.attributes = { 
    user_missions_attributes: { 
      "0" => { mission_title: "Mission A" } } }
  user.save!
  saved_user = User.first
  saved_user.user_missions.size.should == 1

  saved_user.attributes = { 
    user_missions_attributes: { 
      "0" => { :_destroy => '1' } } }
  saved_user.save!
  emptiedUser = User.first
  debugger

  emptiedUser.user_missions.size.should == 0
end

它在找到1 UserMission的最后一行失败。

我正在使用Mongoid 3.0.6和Rails 3.2.8。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要在销毁时加入id_id。 “0”只有user_missions_attributes中的一个键。在哈希中,“0”键需要您实际要删除的文档的ID。如下所示:

"0" => { :_id => ..., :_destroy => '1' }