I have the following models:
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
The problem is I am having trouble deleting a user_mission from a user.
I failed in my view (basically verbatim from a 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>
and I seem to have a problem in the following spec
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
It fails on the last line it finds 1 UserMission.
I am using Mongoid 3.0.6 and Rails 3.2.8. Any help would be appreciated.
You need to include
idor_idwhen destroying. The “0” there is just a key inuser_missions_attributes. Inside the hash that “0” keys to you need the id of the document you actually want to delete. So something like: