I have three documents.
User
List
Food
A list can have many foods and is embedded inside the user document. I have an action in my controller that when an user is done with a food item, loops through the user's list and removes any association between a list and the particular food the user is completed with.
@user.lists.to_a.each do |list|
list.food_ids.to_a.map do |food_id|
if food_id.eql? params[:food_id]
food = Food.find(params[:food_id])
# Pull food from list
list.pull(:foods, food)
end
end
end
@user.save
My models
User
class User
# INCLUDES
# ========
include Mongoid::Document
include Mongoid::Paperclip
include Mongoid::MultiParameterAttributes
include Mongoid::Spacial::Document
# EMBEDDING
# =========
embeds_many :lists
# NESTED ATTRIBUTES
# =================
accepts_nested_attributes_for :lists
end
List
class List
include Mongoid::Document
has_and_belongs_to_many :foods
embedded_in :user
belongs_to: popular_list
end
Food
class Food
# INCLUDES
# ========
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paperclip
include Mongoid::Spacial::Document
# ASSOCIATIONS
# ============
belongs_to :user
has_and_belongs_to_many :popular_lists
end
The problem is, my code does not remove the food item from the list. My question is how can I loop through an array, pull an item from that array, and expect the new array to be saved?
ListandFooddefinitions? Mongoid does not allow references to embedded models and will raise an exception if I try to reproduce this.