Permalink
Browse files

uniq preserves order. References [4325].

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4326 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 50f538b commit d59f3a78a423064f53dadd9f55d05b5f7b2b240e @jeremy jeremy committed May 7, 2006
@@ -109,7 +109,14 @@ def empty?
end
def uniq(collection = self)
- collection.to_set.to_a
+ seen = Set.new
+ collection.inject([]) do |kept, record|
+ unless seen.include?(record.id)
+ kept << record
+ seen << record.id
+ end
+ kept
+ end
end
# Replace this collection with +other_array+
@@ -1278,17 +1278,20 @@ def test_habtm_adding_before_save_with_join_attributes
def test_habtm_saving_multiple_relationships
new_project = Project.new("name" => "Grimetime")
amount_of_developers = 4
- developers = (0..amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }
-
+ developers = (0...amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }.reverse
+
new_project.developer_ids = [developers[0].id, developers[1].id]
new_project.developers_with_callback_ids = [developers[2].id, developers[3].id]
assert new_project.save
-
+
new_project.reload
assert_equal amount_of_developers, new_project.developers.size
- amount_of_developers.times do |i|
- assert_equal developers[i].name, new_project.developers[i].name
- end
+ assert_equal developers, new_project.developers
+ end
+
+ def test_habtm_unique_order_preserved
+ assert_equal [developers(:poor_jamis), developers(:jamis), developers(:david)], projects(:active_record).non_unique_developers
+ assert_equal [developers(:poor_jamis), developers(:jamis), developers(:david)], projects(:active_record).developers
end
def test_build
@@ -1,5 +1,6 @@
class Project < ActiveRecord::Base
- has_and_belongs_to_many :developers, :uniq => true
+ has_and_belongs_to_many :developers, :uniq => true, :order => 'developers.name desc, developers.id desc'
+ has_and_belongs_to_many :non_unique_developers, :order => 'developers.name desc, developers.id desc', :class_name => 'Developer'
has_and_belongs_to_many :limited_developers, :class_name => "Developer", :limit => 1
has_and_belongs_to_many :developers_named_david, :class_name => "Developer", :conditions => "name = 'David'", :uniq => true
has_and_belongs_to_many :salaried_developers, :class_name => "Developer", :conditions => "salary > 0"

0 comments on commit d59f3a7

Please sign in to comment.