Sql ActiveRecord查询两次返回对象(同一对象的两个实例)
我的查询可能有问题,不确定具体是什么Sql ActiveRecord查询两次返回对象(同一对象的两个实例),sql,ruby-on-rails,ruby-on-rails-4,activerecord,Sql,Ruby On Rails,Ruby On Rails 4,Activerecord,我的查询可能有问题,不确定具体是什么 # this is the correct output Plan.select { |p| p.plan_dates.select { |pd| pd.ddate.to_date >= cancel_from_this_date }.count > 0 }.map(&:id) # => [54] # this is the output where the object is returned twice Plan.joins(
# this is the correct output
Plan.select { |p| p.plan_dates.select { |pd| pd.ddate.to_date >= cancel_from_this_date }.count > 0 }.map(&:id)
# => [54]
# this is the output where the object is returned twice
Plan.joins(:plan_dates).where("plan_dates.ddate >= ?", cancel_from_this_date.in_time_zone).pluck("id")
# => [54, 54]
这是很自然的
Plan.joins(:Plan\u dates)
为所有具有PlanDate的计划返回一个计划对象
现在,如果多个计划日期
有一个计划
,您将得到重复的计划
要解决此问题,您需要使用uniq,如下所示:
Plan.join(:Plan\u dates).uniq.where(“Plan\u dates.ddate>=?”,从这个日期取消。在时区)。点击(“id”)
欢迎您。你可以在ugh学习更多,我读了整件事,但我仍然遇到了无数的问题。如果我能帮忙的话,你可以提到它们吗?是的,上帝是的:1),2)因此,一个基于模型的查询,通过另一个表的连接值进行过滤,可以返回作为要过滤的集合传递的实例的副本(其目的是通过仅返回原始集合中的匹配值来“减少”集合)。一个应该是减法的步骤产生了绝对疯狂的意外结果-并且很难跟踪。谢谢!!!