Ruby on rails 在rails中查找没有nil关联的活动记录条目

Ruby on rails 在rails中查找没有nil关联的活动记录条目,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,这些显然不是我的实际模型,但它们只是一个例子。我有以下的类定义 class Movie < ActiveRecord::Base has_one :opening has_one :opening_info, through: :opening end class Opening < ActiveRecord::Base belongs_to :movie has_one :opening_info end class OpeningInfo &l

这些显然不是我的实际模型,但它们只是一个例子。我有以下的类定义

class Movie < ActiveRecord::Base
    has_one :opening
    has_one :opening_info, through: :opening
end

class Opening < ActiveRecord::Base
    belongs_to :movie
    has_one :opening_info
end

class OpeningInfo < ActiveRecord::Base
    belongs_to :opening
    # OpeningInfo has a opening_date attribute in the DB
end

但是这个查询很慢,大约2/3秒,理想情况下,我希望它不会比其他普通查询花费更长的时间,大约100-500毫秒。rails是如何做到这一点的?

您是否为正在查询的列添加了索引?这将大大加快速度。

找到了答案

Movie.includes(:opening, :opening_info).where("opening_infos.opening_date is null or opening_infos is null or openings is null")

是的,不管怎样,我只是好奇。集减法似乎是一个笨拙的解决方案。
Movie.includes(:opening, :opening_info).where("opening_infos.opening_date is null or opening_infos is null or openings is null")