2

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]

1 Answer 1

2

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")

Sign up to request clarification or add additional context in comments.

5 Comments

your welcome. you can study more at guides.rubyonrails.org/active_record_querying.html
ugh i read that whole thing but i still am running into a zillion problems
can you mention them, if i can help?
So, a Model-based query, filtered through another table's values with join, can return duplicates of the instances passed as the set to be filtered (the intention being to 'reduce' the set by returning only the matching values from the original-set). Absolutely crazy unexpected result from a step which should be subtractive - and quite difficult to track down. Thank you!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.