Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Sep 24, 2025

Addresses the issue where users could only use distinct: true to generate SELECT DISTINCT on all columns, with no way to specify which specific columns should be included in the DISTINCT clause.

What's Changed

Previously, users were limited to:

@q.result(distinct: true)  # SELECT DISTINCT * FROM table
@q.result                  # No DISTINCT clause

Now users can specify exactly which columns to use in the DISTINCT clause:

# Single column as string or symbol
@q.result(distinct: 'name')
@q.result(distinct: :email)

# Multiple columns as array
@q.result(distinct: [:name, :email])
@q.result(distinct: ['name', 'email', 'created_at'])

# Explicit control over DISTINCT behavior
@q.result(distinct: false)  # No DISTINCT (explicit)
@q.result(distinct: nil)    # No DISTINCT
@q.result(distinct: [])     # SELECT DISTINCT * (fallback)

Implementation Details

  • Core changes: Modified lib/ransack/adapters/active_record/context.rb to handle various distinct option types
  • Backward compatible: All existing distinct: true usage continues to work unchanged
  • Flexible input: Accepts strings, symbols, arrays, and mixed types
  • Edge case handling: Properly handles false, nil, empty arrays
  • ActiveRecord native: Uses ActiveRecord's built-in distinct(*columns) method

Benefits

This eliminates the need for workarounds that users previously had to employ:

# Before: Manual workarounds
@q.result(distinct: true)
  .select('people.*, articles.name, articles.description')

# Before: Using group instead of distinct  
@q.result.group('people.id').includes(:articles)

# Now: Direct and clean
@q.result(distinct: [:name, :email])

Testing

Added comprehensive test coverage including:

  • All supported data types (string, symbol, array, boolean, nil)
  • Edge cases and mixed type arrays
  • SQL generation validation
  • Backward compatibility verification

Documentation

Updated the "Problem with DISTINCT selects" section in the documentation with examples and a complete reference of supported option types.

Fixes the issue where users needed to work around distinct limitations with manual column selection or alternative approaches like grouping.

Fixes #1533


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@Copilot Copilot AI changed the title [WIP] select distinct on specific columns Add support for specifying distinct columns in result queries Sep 24, 2025
@Copilot Copilot AI requested a review from scarroll32 September 24, 2025 14:13
Copilot finished work on behalf of scarroll32 September 24, 2025 14:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

select distinct on specific columns
2 participants