检查关系是否存在has_one mongoid

时间:2013-12-28 14:01:09

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 mongoid

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 

但是,所有questions都创建并关联了一个response

谢谢!

1 个答案:

答案 0 :(得分:4)

ID字段仅存储在子对象中,因此Question不知道其Response(无response_id字段)。

你可以达到这样的目标:

Response.ne(question_id: nil).map(&:question)

或者,在没有回复的情况下获取问题:

Question.not.in(id: Response.pluck(:question_id))