如何使用mongoid插入而不必进行额外的查询


有什么

方法可以防止在执行此操作时必须查询数据库以获取问题。

has_and_belongs_to_many :followed_questions,  class_name: 'Question', inverse_of: nil
qid = "501928374"
q = Question.find(qid)
self.followed_questions << q unless self.followed_questions.include?(q)
self.save

我想这样做:

has_and_belongs_to_many :followed_questions,  class_name: 'Question', inverse_of: nil
qid = "501928374"    
self.followed_questions << qid unless self.followed_questions.include?(qid)
self.save

是的,您可以通过分配 ID 而不是文档来做到这一点

has_and_belongs_to_many :followed_questions,  class_name: 'Question', inverse_of: nil
qid = "501928374"    
self.followed_question_ids << qid unless self.followed_question_ids.include?(qid)
self.save

相关内容

最新更新