mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
uniq preserves order. References [4325].
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4326 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
parent
50f538b72b
commit
d59f3a78a4
3 changed files with 19 additions and 8 deletions
|
@ -109,7 +109,14 @@ module ActiveRecord
|
|||
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,7 +1278,7 @@ class HasAndBelongsToManyAssociationsTest < Test::Unit::TestCase
|
|||
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]
|
||||
|
@ -1286,9 +1286,12 @@ class HasAndBelongsToManyAssociationsTest < Test::Unit::TestCase
|
|||
|
||||
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
|
||||
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
|
||||
|
|
3
activerecord/test/fixtures/project.rb
vendored
3
activerecord/test/fixtures/project.rb
vendored
|
@ -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"
|
||||
|
|
Loading…
Reference in a new issue