0

我有三个文件。

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

问题是,我的代码不会从列表中删除食物项目。我的问题是如何遍历一个数组,从该数组中拉出一个项目,并期望保存新数组?

4

1 回答 1

1

由于两个问题,它不起作用:首先,您不能 embed List,因为您有来自/到它的引用(关系)。用普通的belongs_to :user.

You cannot have relations to embedded models, because the other side will only store the id. If you use that relation, Mongoid will call MyEmbeddedModel.find(related_id) which cannot find the embedded model, because it's inside another document and not an own collection.

Second, your code is missing the counterparts for belongs_to :user and has_and_belongs_to_many :foods. The documentation states: Definitions are required on both sides to the relation in order for it to work properly. If you add these (see my gist), Mongoid will raise an error that also suggests not to embed List:

(Mongoid::Errors::MixedRelations)

Problem: Referencing a(n) List document from the Food document via a relational association is not allowed since the List is embedded.

Summary: In order to properly access a(n) List from Food the reference would need to go through the root document of List. In a simple case this would require Mongoid to store an extra foreign key for the root, in more complex cases where List is multiple levels deep a key would need to be stored for each parent up the hierarchy. Resolution: Consider not embedding List, or do the key storage and access in a custom manner in the application code.

于 2013-03-30T00:03:54.590 回答