james
james

Reputation: 4049

ActiveRecord query returns object twice (2 instances of same object)

Something is probably wrong with my query, not sure exactly what...

# 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]

Upvotes: 2

Views: 625

Answers (1)

abhinavmsra
abhinavmsra

Reputation: 666

It is quite natural.

Plan.joins(:plan_dates) returns a Plan object for all Plan with PlanDate.

Now, if multiple plan_dates have single Plan, you will get duplicate plans.

To resolve this, you need to use uniq as follows:

Plan.joins(:plan_dates).uniq.where("plan_dates.ddate >= ?", cancel_from_this_date.in_time_zone).pluck("id")

Upvotes: 2

Related Questions