class Question
include Mongoid::Document
include Mongoid::Timestamps
field :title, :type => String
has_one :response
end
class Response
include Mongoid::Document
include Mongoid::Timestamps
field :content, :type => String
belongs_to :question
end
控制台:
1.9.3p448 :014 > Question.where(:response => nil).size
=> 3
1.9.3p448 :016 > Question.where(:response.ne => nil).size
=> 0
然而,所有问题
都有一个创建并关联的response
!
谢谢!
最佳答案
ID 字段仅存储在子对象中,因此 Question
不知道它的 Response
(没有 response_id
字段)。
你可以这样实现目标:
Response.ne(question_id: nil).map(&:question)
或者,获取没有回复的问题:
Question.not.in(id: Response.pluck(:question_id))
关于ruby-on-rails - 检查关系是否存在 has_one mongoid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20815417/