我有三个文件。
User
List
Food
一个列表可以包含许多食物,并且嵌入在用户文档中。我的控制器中有一个动作,当用户完成食物项目时,循环遍历用户的列表并删除列表与用户完成的特定食物之间的任何关联。
@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
我的模型
用户
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
列表
class List
include Mongoid::Document
has_and_belongs_to_many :foods
embedded_in :user
belongs_to: popular_list
end
食物
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
问题是,我的代码不会从列表中删除食物项目。我的问题是如何遍历一个数组,从该数组中拉出一个项目,并期望保存新数组?