alecdotninja / active_record_distinct_on

Support for `DISTINCT ON` statements when querying with ActiveRecord
MIT License
34 stars 11 forks source link

distinct_on doesn't work within has_many scope #18

Closed Hampei closed 2 years ago

Hampei commented 2 years ago

Using distinct_on within a has_many scope, does not throw an error, but seems to be completely ignored.

has_many :leaves, -> { distinct_on(:id) }, through: :branches
>  tree.leaves.to_sql
=> "select leaves.* from leaves inner join ..."

> tree.leaves.distinct_on(:id).to_sql
=> "select  distinct  on (leaves.id) leaves.*  from leaves inner join ..."

What is needed is that ActiveRecord::Relation::Merger::NORMAL_VALUES needs distinct_on added as well, but for that to work distinct_on! needs to save the given input without the mapping to arel attributes, since that will happen multiple times then. The mapping should be moved to the build_distinct_on.

alecdotninja commented 2 years ago

Thank you for your work on this, @Hampei !

The fix for this issue has been released in version 1.4.0. :tada: