This project is archived and is in readonly mode.

#6202 ✓stale
Blake Smith

[PATCH] has_many :through _ids collection_reader methods should honor :uniq option

Reported by Blake Smith | December 21st, 2010 @ 03:46 PM

Hello there,

I've found what I believe to be a bug in the 2-3-stable branch. Given a model that contains a has_many :through association that uses the :uniq option like so:

class User < ActiveRecord::Base
  has_many :user_events
  has_many :events, :through => :user_events, :uniq => true
end

class UserEvent < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :user_events
  has_many :users, :through => :user_events
end

When I make a call for the elemnts of the unique association, the query generated uses a SELECT DISTINCT query like expected:

ree-1.8.7-2010.02 > u = User.first
ree-1.8.7-2010.02 > u.events
  Event Load (0.3ms)   SELECT DISTINCT "events".* FROM "events" INNER JOIN "user_events" ON "events".id = "user_events".event_id WHERE (("user_events".user_id = 1)) 
 => [#<Event id: 1, user_event_id: nil>]

However, when I make the call on the association's _ids method, it does not generate a DISTINCT query.

ree-1.8.7-2010.02 > u.event_ids
  Event Load (0.2ms)   SELECT "events".id FROM "events" INNER JOIN "user_events" ON "events".id = "user_events".event_id WHERE (("user_events".user_id = 1))

The expected behavior does seem to be working properly in Rails 3, attached is a patch that backports this behavior to the rails 2-3-stable branch.

Thanks!

Blake

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Attachments

Pages