0

我有以下型号:

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。任何帮助,将不胜感激。

4

1 回答 1

0

您需要包括id_id销毁时。“0”只有一个键user_missions_attributes。在“0”键的散列中,您需要实际要删除的文档的 ID。所以像:

"0" => { :_id => ..., :_destroy => '1' }
于 2012-10-04T07:41:21.157 回答