aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2010-11-17 11:32:31 +0000
committerJon Leighton <j@jonathanleighton.com>2010-11-17 11:32:31 +0000
commit1bc90044b655572a4b8aa3b323905e26d37e0f2b (patch)
tree84a2d67b24e149b703308c892d1ec37a1019103b /activerecord
parente05162cffad7ae86615c21c6b54ab161d0261c39 (diff)
parent401c1835afb5af1a6f429061ac8484227c34909d (diff)
downloadrails-1bc90044b655572a4b8aa3b323905e26d37e0f2b.tar.gz
rails-1bc90044b655572a4b8aa3b323905e26d37e0f2b.tar.bz2
rails-1bc90044b655572a4b8aa3b323905e26d37e0f2b.zip
Merge branch 'master' into nested_has_many_through
Conflicts: activerecord/lib/active_record/associations/has_many_through_association.rb activerecord/test/cases/associations/has_many_through_associations_test.rb
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/CHANGELOG29
-rw-r--r--activerecord/activerecord.gemspec2
-rw-r--r--activerecord/lib/active_record/aggregations.rb2
-rw-r--r--activerecord/lib/active_record/associations.rb2
-rw-r--r--activerecord/lib/active_record/associations/association_collection.rb50
-rw-r--r--activerecord/lib/active_record/associations/association_proxy.rb10
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb6
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb5
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb12
-rw-r--r--activerecord/lib/active_record/associations/has_one_through_association.rb2
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb7
-rw-r--r--activerecord/lib/active_record/autosave_association.rb14
-rw-r--r--activerecord/lib/active_record/base.rb28
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb2
-rw-r--r--activerecord/lib/active_record/locking/pessimistic.rb2
-rw-r--r--activerecord/lib/active_record/migration.rb2
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb2
-rw-r--r--activerecord/lib/active_record/persistence.rb11
-rw-r--r--activerecord/lib/active_record/railtie.rb2
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb39
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb2
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb5
-rw-r--r--activerecord/lib/active_record/session_store.rb9
-rw-r--r--activerecord/lib/active_record/transactions.rb12
-rw-r--r--activerecord/lib/active_record/validations.rb2
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb2
-rw-r--r--activerecord/lib/active_record/version.rb4
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb12
-rw-r--r--activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb2
-rw-r--r--activerecord/test/cases/associations/eager_test.rb12
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb32
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb60
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb7
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb4
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb4
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb16
-rw-r--r--activerecord/test/cases/associations_test.rb2
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb2
-rw-r--r--activerecord/test/cases/autosave_association_test.rb92
-rw-r--r--activerecord/test/cases/base_test.rb24
-rw-r--r--activerecord/test/cases/calculations_test.rb13
-rw-r--r--activerecord/test/cases/finder_test.rb54
-rw-r--r--activerecord/test/cases/fixtures_test.rb6
-rw-r--r--activerecord/test/cases/migration_test.rb23
-rw-r--r--activerecord/test/cases/named_scope_test.rb2
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb24
-rw-r--r--activerecord/test/cases/persistence_test.rb12
-rw-r--r--activerecord/test/cases/query_cache_test.rb1
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb2
-rw-r--r--activerecord/test/cases/relations_test.rb35
-rw-r--r--activerecord/test/cases/session_store/sql_bypass.rb4
-rw-r--r--activerecord/test/cases/timestamp_test.rb2
-rw-r--r--activerecord/test/cases/transactions_test.rb18
-rw-r--r--activerecord/test/cases/validations/association_validation_test.rb4
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb4
-rw-r--r--activerecord/test/models/eye.rb2
-rw-r--r--activerecord/test/models/pirate.rb2
-rw-r--r--activerecord/test/models/subject.rb2
-rw-r--r--activerecord/test/models/topic.rb2
60 files changed, 461 insertions, 287 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 06c1428217..29f06dc06a 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -20,6 +20,35 @@
[Aaron Patterson]
+*Rails 3.0.2 (unreleased)*
+
+* reorder is deprecated in favor of except(:order).order(...) [Santiago Pastorino]
+
+* except is now AR public API
+
+ Model.order('name').except(:order).order('salary')
+
+ generates:
+
+ SELECT * FROM models ORDER BY salary
+
+ [Santiago Pastorino]
+
+* The following code:
+
+ Model.limit(10).scoping { Model.count }
+
+ now generates the following SQL:
+
+ SELECT COUNT(*) FROM models LIMIT 10
+
+ This may not return what you want. Instead, you may with to do something
+ like this:
+
+ Model.limit(10).scoping { Model.all.size }
+
+ [Aaron Patterson]
+
*Rails 3.0.1 (October 15, 2010)*
* Introduce a fix for CVE-2010-3993
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index b8a980b1fb..b1df24844a 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -23,6 +23,6 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
- s.add_dependency('arel', '~> 2.0.0')
+ s.add_dependency('arel', '~> 2.0.2')
s.add_dependency('tzinfo', '~> 0.3.23')
end
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index 16206c1056..8cd7389005 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -6,7 +6,7 @@ module ActiveRecord
def clear_aggregation_cache #:nodoc:
self.class.reflect_on_all_aggregations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
- end unless self.new_record?
+ end if self.persisted?
end
# Active Record implements aggregation through a macro-like class method called +composed_of+
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 577a807e3c..e82cbd0aa6 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -117,7 +117,7 @@ module ActiveRecord
def clear_association_cache #:nodoc:
self.class.reflect_on_all_associations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
- end unless self.new_record?
+ end if self.persisted?
end
private
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb
index 896e18af01..6090376bb8 100644
--- a/activerecord/lib/active_record/associations/association_collection.rb
+++ b/activerecord/lib/active_record/associations/association_collection.rb
@@ -75,6 +75,7 @@ module ActiveRecord
find(:first, *args)
else
load_target unless loaded?
+ args = args[1..-1] if args.first.kind_of?(Hash) && args.first.empty?
@target.first(*args)
end
end
@@ -120,13 +121,13 @@ module ActiveRecord
# Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
def <<(*records)
result = true
- load_target if @owner.new_record?
+ load_target unless @owner.persisted?
transaction do
flatten_deeper(records).each do |record|
raise_on_type_mismatch(record)
add_record_to_target_with_callbacks(record) do |r|
- result &&= insert_record(record) unless @owner.new_record?
+ result &&= insert_record(record) if @owner.persisted?
end
end
end
@@ -181,7 +182,7 @@ module ActiveRecord
unless options.blank?
raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
end
-
+
@reflection.klass.count_by_sql(custom_counter_sql)
else
@@ -285,12 +286,12 @@ module ActiveRecord
# This method is abstract in the sense that it relies on
# +count_records+, which is a method descendants have to provide.
def size
- if @owner.new_record? || (loaded? && !@reflection.options[:uniq])
+ if !@owner.persisted? || (loaded? && !@reflection.options[:uniq])
@target.size
elsif !loaded? && @reflection.options[:group]
load_target.size
elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array)
- unsaved_records = @target.select { |r| r.new_record? }
+ unsaved_records = @target.reject { |r| r.persisted? }
unsaved_records.size + count_records
else
count_records
@@ -331,13 +332,10 @@ module ActiveRecord
end
def uniq(collection = self)
- seen = Set.new
- collection.map do |record|
- unless seen.include?(record.id)
- seen << record.id
- record
- end
- end.compact
+ seen = {}
+ collection.find_all do |record|
+ seen[record.id] = true unless seen.key?(record.id)
+ end
end
# Replace this collection with +other_array+
@@ -357,7 +355,7 @@ module ActiveRecord
def include?(record)
return false unless record.is_a?(@reflection.klass)
- return include_in_memory?(record) if record.new_record?
+ return include_in_memory?(record) unless record.persisted?
load_target if @reflection.options[:finder_sql] && !loaded?
return @target.include?(record) if loaded?
exists?(record)
@@ -372,16 +370,18 @@ module ActiveRecord
end
def load_target
- if !@owner.new_record? || foreign_key_present
+ if @owner.persisted? || foreign_key_present
begin
- if !loaded?
+ unless loaded?
if @target.is_a?(Array) && @target.any?
@target = find_target.map do |f|
i = @target.index(f)
if i
@target.delete_at(i).tap do |t|
keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
- t.attributes = f.attributes.except(*keys)
+ f.attributes.except(*keys).each do |k,v|
+ t.send("#{k}=", v)
+ end
end
else
f
@@ -408,11 +408,7 @@ module ActiveRecord
end
if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
- if block_given?
- super { |*block_args| yield(*block_args) }
- else
- super
- end
+ super
elsif @reflection.klass.scopes[method]
@_named_scopes_cache ||= {}
@_named_scopes_cache[method] ||= {}
@@ -435,10 +431,10 @@ module ActiveRecord
# replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
counter_sql = @reflection.options[:finder_sql].sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
end
-
+
interpolate_sql(counter_sql)
end
-
+
def custom_finder_sql
interpolate_sql(@reflection.options[:finder_sql])
end
@@ -513,7 +509,7 @@ module ActiveRecord
transaction do
records.each { |record| callback(:before_remove, record) }
- old_records = records.reject { |r| r.new_record? }
+ old_records = records.select { |r| r.persisted? }
yield(records, old_records)
records.each { |record| callback(:after_remove, record) }
end
@@ -538,14 +534,14 @@ module ActiveRecord
end
def ensure_owner_is_not_new
- if @owner.new_record?
+ unless @owner.persisted?
raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
end
end
def fetch_first_or_last_using_find?(args)
- args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] ||
- @target.any? { |record| record.new_record? } || args.first.kind_of?(Integer))
+ (args.first.kind_of?(Hash) && !args.first.empty?) || !(loaded? || !@owner.persisted? || @reflection.options[:finder_sql] ||
+ !@target.all? { |record| record.persisted? } || args.first.kind_of?(Integer))
end
def include_in_memory?(record)
diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb
index ac2aa46edf..7cd04a1ad5 100644
--- a/activerecord/lib/active_record/associations/association_proxy.rb
+++ b/activerecord/lib/active_record/associations/association_proxy.rb
@@ -175,10 +175,10 @@ module ActiveRecord
# If the association is polymorphic the type of the owner is also set.
def set_belongs_to_association_for(record)
if @reflection.options[:as]
- record["#{@reflection.options[:as]}_id"] = @owner.id unless @owner.new_record?
+ record["#{@reflection.options[:as]}_id"] = @owner.id if @owner.persisted?
record["#{@reflection.options[:as]}_type"] = @owner.class.base_class.name.to_s
else
- unless @owner.new_record?
+ if @owner.persisted?
primary_key = @reflection.options[:primary_key] || :id
record[@reflection.primary_key_name] = @owner.send(primary_key)
end
@@ -211,12 +211,12 @@ module ActiveRecord
:create => construct_create_scope
}
end
-
+
# Implemented by subclasses
def construct_find_scope
raise NotImplementedError
end
-
+
# Implemented by (some) subclasses
def construct_create_scope
{}
@@ -252,7 +252,7 @@ module ActiveRecord
def load_target
return nil unless defined?(@loaded)
- if !loaded? and (!@owner.new_record? || foreign_key_present)
+ if !loaded? and (@owner.persisted? || foreign_key_present)
@target = find_target
end
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index 34b6cd5576..b624951cd9 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -14,7 +14,7 @@ module ActiveRecord
counter_cache_name = @reflection.counter_cache_column
if record.nil?
- if counter_cache_name && !@owner.new_record?
+ if counter_cache_name && @owner.persisted?
@reflection.klass.decrement_counter(counter_cache_name, previous_record_id) if @owner[@reflection.primary_key_name]
end
@@ -22,13 +22,13 @@ module ActiveRecord
else
raise_on_type_mismatch(record)
- if counter_cache_name && !@owner.new_record? && record.id != @owner[@reflection.primary_key_name]
+ if counter_cache_name && @owner.persisted? && record.id != @owner[@reflection.primary_key_name]
@reflection.klass.increment_counter(counter_cache_name, record.id)
@reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
end
@target = (AssociationProxy === record ? record.target : record)
- @owner[@reflection.primary_key_name] = record_id(record) unless record.new_record?
+ @owner[@reflection.primary_key_name] = record_id(record) if record.persisted?
@updated = true
end
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
index 1fc9aba5cf..da742fa668 100644
--- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
@@ -34,7 +34,7 @@ module ActiveRecord
end
def insert_record(record, force = true, validate = true)
- if record.new_record?
+ unless record.persisted?
if force
record.save!
else
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index c45f2ee224..c1fc16b0ed 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -67,7 +67,7 @@ module ActiveRecord
def insert_record(record, force = true, validate = true)
ensure_not_nested
- if record.new_record?
+ unless record.persisted?
if force
record.save!
else
@@ -76,8 +76,7 @@ module ActiveRecord
end
through_association = @owner.send(@reflection.through_reflection.name)
- through_record = through_association.create!(construct_join_attributes(record))
- through_association.proxy_target << through_record
+ through_association.create!(construct_join_attributes(record))
end
# TODO - add dependent option support
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index c6bcfec275..0ccf07f15e 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -30,18 +30,18 @@ module ActiveRecord
if dependent? && !dont_save
case @reflection.options[:dependent]
when :delete
- @target.delete unless @target.new_record?
+ @target.delete if @target.persisted?
@owner.clear_association_cache
when :destroy
- @target.destroy unless @target.new_record?
+ @target.destroy if @target.persisted?
@owner.clear_association_cache
when :nullify
@target[@reflection.primary_key_name] = nil
- @target.save unless @owner.new_record? || @target.new_record?
+ @target.save if @owner.persisted? && @target.persisted?
end
else
@target[@reflection.primary_key_name] = nil
- @target.save unless @owner.new_record? || @target.new_record?
+ @target.save if @owner.persisted? && @target.persisted?
end
end
@@ -56,7 +56,7 @@ module ActiveRecord
set_inverse_instance(obj, @owner)
@loaded = true
- unless @owner.new_record? or obj.nil? or dont_save
+ unless !@owner.persisted? or obj.nil? or dont_save
return (obj.save ? self : false)
else
return (obj.nil? ? nil : self)
@@ -113,7 +113,7 @@ module ActiveRecord
if replace_existing
replace(record, true)
else
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
+ record[@reflection.primary_key_name] = @owner.id if @owner.persisted?
self.target = record
set_inverse_instance(record, @owner)
end
diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb
index e9dc32efd3..cfd4637e8e 100644
--- a/activerecord/lib/active_record/associations/has_one_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -23,7 +23,7 @@ module ActiveRecord
if current_object
new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
elsif new_value
- if @owner.new_record?
+ unless @owner.persisted?
self.target = new_value
through_association = @owner.send(:association_instance_get, @reflection.through_reflection.name)
through_association.build(construct_join_attributes(new_value))
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
index 82d94b848a..75ae06f5e9 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -3,10 +3,11 @@ module ActiveRecord
module PrimaryKey
extend ActiveSupport::Concern
- # Returns this record's primary key value wrapped in an Array
- # or nil if the record is a new_record?
+ # Returns this record's primary key value wrapped in an Array or nil if
+ # the record is not persisted? or has just been destroyed.
def to_key
- new_record? ? nil : [ id ]
+ key = send(self.class.primary_key)
+ [key] if key
end
module ClassMethods
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 0b89a49896..cb5bc06580 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -217,7 +217,7 @@ module ActiveRecord
# Returns whether or not this record has been changed in any way (including whether
# any of its nested autosave associations are likewise changed)
def changed_for_autosave?
- new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
+ !persisted? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
end
private
@@ -231,7 +231,7 @@ module ActiveRecord
elsif autosave
association.target.find_all { |record| record.changed_for_autosave? }
else
- association.target.find_all { |record| record.new_record? }
+ association.target.find_all { |record| !record.persisted? }
end
end
@@ -257,7 +257,7 @@ module ActiveRecord
# +reflection+.
def validate_collection_association(reflection)
if association = association_instance_get(reflection.name)
- if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
+ if records = associated_records_to_validate_or_save(association, !persisted?, reflection.options[:autosave])
records.each { |record| association_valid?(reflection, record) }
end
end
@@ -286,7 +286,7 @@ module ActiveRecord
# Is used as a before_save callback to check while saving a collection
# association whether or not the parent was a new record before saving.
def before_save_collection_association
- @new_record_before_save = new_record?
+ @new_record_before_save = !persisted?
true
end
@@ -308,7 +308,7 @@ module ActiveRecord
if autosave && record.marked_for_destruction?
association.destroy(record)
- elsif autosave != false && (@new_record_before_save || record.new_record?)
+ elsif autosave != false && (@new_record_before_save || !record.persisted?)
if autosave
saved = association.send(:insert_record, record, false, false)
else
@@ -343,7 +343,7 @@ module ActiveRecord
association.destroy
else
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
- if autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != key || autosave)
+ if autosave != false && (!persisted? || !association.persisted? || association[reflection.primary_key_name] != key || autosave)
association[reflection.primary_key_name] = key
saved = association.save(:validate => !autosave)
raise ActiveRecord::Rollback if !saved && autosave
@@ -363,7 +363,7 @@ module ActiveRecord
if autosave && association.marked_for_destruction?
association.destroy
elsif autosave != false
- saved = association.save(:validate => !autosave) if association.new_record? || autosave
+ saved = association.save(:validate => !autosave) if !association.persisted? || autosave
if association.updated?
association_id = association.send(reflection.options[:primary_key] || :id)
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 06a388cd21..b35f59d6df 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -204,7 +204,7 @@ module ActiveRecord #:nodoc:
#
# # No 'Winter' tag exists
# winter = Tag.find_or_initialize_by_name("Winter")
- # winter.new_record? # true
+ # winter.persisted? # false
#
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
# a list of parameters.
@@ -1368,7 +1368,7 @@ MSG
def initialize(attributes = nil)
@attributes = attributes_from_column_definition
@attributes_cache = {}
- @new_record = true
+ @persisted = false
@readonly = false
@destroyed = false
@marked_for_destruction = false
@@ -1403,7 +1403,7 @@ MSG
clear_aggregation_cache
clear_association_cache
@attributes_cache = {}
- @new_record = true
+ @persisted = false
ensure_proper_type
populate_with_current_scope_attributes
@@ -1422,7 +1422,8 @@ MSG
def init_with(coder)
@attributes = coder['attributes']
@attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
- @new_record = @readonly = @destroyed = @marked_for_destruction = false
+ @readonly = @destroyed = @marked_for_destruction = false
+ @persisted = true
_run_find_callbacks
_run_initialize_callbacks
end
@@ -1463,7 +1464,7 @@ MSG
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
def cache_key
case
- when new_record?
+ when !persisted?
"#{self.class.model_name.cache_key}/new"
when timestamp = self[:updated_at]
"#{self.class.model_name.cache_key}/#{id}-#{timestamp.to_s(:number)}"
@@ -1581,11 +1582,20 @@ MSG
self.class.columns_hash[name.to_s]
end
- # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
+ # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
+ # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
+ #
+ # Note that new records are different from any other record by definition, unless the
+ # other record is the receiver itself. Besides, if you fetch existing records with
+ # +select+ and leave the ID out, you're on your own, this predicate will return false.
+ #
+ # Note also that destroying a record preserves its ID in the model instance, so deleted
+ # models are still comparable.
def ==(comparison_object)
comparison_object.equal?(self) ||
- (comparison_object.instance_of?(self.class) &&
- comparison_object.id == id && !comparison_object.new_record?)
+ comparison_object.instance_of?(self.class) &&
+ id.present? &&
+ comparison_object.id == id
end
# Delegates to ==
@@ -1630,7 +1640,7 @@ MSG
# Returns the contents of the record as a nicely formatted string.
def inspect
attributes_as_nice_string = self.class.column_names.collect { |name|
- if has_attribute?(name) || new_record?
+ if has_attribute?(name) || !persisted?
"#{name}: #{attribute_for_inspect(name)}"
end
}.compact.join(", ")
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index b6f87a57b8..bf626301f1 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -109,7 +109,7 @@ module ActiveRecord
def destroy #:nodoc:
return super unless locking_enabled?
- unless new_record?
+ if persisted?
lock_col = self.class.locking_column
previous_value = send(lock_col).to_i
diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb
index 9ad6a2baf7..d900831e13 100644
--- a/activerecord/lib/active_record/locking/pessimistic.rb
+++ b/activerecord/lib/active_record/locking/pessimistic.rb
@@ -47,7 +47,7 @@ module ActiveRecord
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
# the locked record.
def lock!(lock = true)
- reload(:lock => lock) unless new_record?
+ reload(:lock => lock) if persisted?
self
end
end
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index a4c09b654a..2c306d233a 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -387,6 +387,8 @@ module ActiveRecord
def copy(destination, sources, options = {})
copied = []
+ FileUtils.mkdir_p(destination) unless File.exists?(destination)
+
destination_migrations = ActiveRecord::Migrator.migrations(destination)
last = destination_migrations.last
sources.each do |name, path|
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index aca91c907d..0c3392263a 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -323,7 +323,7 @@ module ActiveRecord
(options[:update_only] || record.id.to_s == attributes['id'].to_s)
assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
- elsif attributes['id']
+ elsif attributes['id'].present?
raise_nested_attributes_record_not_found(association_name, attributes['id'])
elsif !reject_new_record?(association_name, attributes)
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 707c1a05be..594a2214bb 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -4,7 +4,7 @@ module ActiveRecord
# Returns true if this object hasn't been saved yet -- that is, a record
# for the object doesn't exist in the data store yet; otherwise, returns false.
def new_record?
- @new_record
+ !@persisted
end
# Returns true if this object has been destroyed, otherwise returns false.
@@ -15,7 +15,7 @@ module ActiveRecord
# Returns if the record is persisted, i.e. it's not a new record and it was
# not destroyed.
def persisted?
- !(new_record? || destroyed?)
+ @persisted && !destroyed?
end
# Saves the model.
@@ -94,8 +94,9 @@ module ActiveRecord
became = klass.new
became.instance_variable_set("@attributes", @attributes)
became.instance_variable_set("@attributes_cache", @attributes_cache)
- became.instance_variable_set("@new_record", new_record?)
+ became.instance_variable_set("@persisted", persisted?)
became.instance_variable_set("@destroyed", destroyed?)
+ became.type = klass.name unless self.class.descends_from_active_record?
became
end
@@ -240,7 +241,7 @@ module ActiveRecord
private
def create_or_update
raise ReadOnlyRecord if readonly?
- result = new_record? ? create : update
+ result = persisted? ? update : create
result != false
end
@@ -269,7 +270,7 @@ module ActiveRecord
self.id ||= new_id
- @new_record = false
+ @persisted = true
id
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 868fd6c3ff..dfe255ad7c 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -14,7 +14,7 @@ module ActiveRecord
config.active_record = ActiveSupport::OrderedOptions.new
config.app_generators.orm :active_record, :migration => true,
- :timestamps => true
+ :timestamps => true
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
"ActiveRecord::QueryCache"
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 6bf698fe97..c8adaddfca 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -208,14 +208,16 @@ module ActiveRecord
end
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
- group_attr = @group_values.first
- association = @klass.reflect_on_association(group_attr.to_sym)
- associated = association && association.macro == :belongs_to # only count belongs_to associations
- group_field = associated ? association.primary_key_name : group_attr
- group_alias = column_alias_for(group_field)
- group_column = column_for(group_field)
+ group_attr = @group_values
+ association = @klass.reflect_on_association(group_attr.first.to_sym)
+ associated = group_attr.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
+ group_fields = Array(associated ? association.primary_key_name : group_attr)
+ group_aliases = group_fields.map { |field| column_alias_for(field) }
+ group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
+ [aliaz, column_for(field)]
+ }
- group = @klass.connection.adapter_name == 'FrontBase' ? group_alias : group_field
+ group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
if operation == 'count' && column_name == :all
aggregate_alias = 'count_all'
@@ -223,22 +225,33 @@ module ActiveRecord
aggregate_alias = column_alias_for(operation, column_name)
end
- relation = except(:group).group(group)
- relation.select_values = [
- operation_over_aggregate_column(aggregate_column(column_name), operation, distinct).as(aggregate_alias),
- "#{group_field} AS #{group_alias}"
+ select_values = [
+ operation_over_aggregate_column(
+ aggregate_column(column_name),
+ operation,
+ distinct).as(aggregate_alias)
]
+ select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
+ "#{field} AS #{aliaz}"
+ }
+
+ relation = except(:group).group(group.join(','))
+ relation.select_values = select_values
+
calculated_data = @klass.connection.select_all(relation.to_sql)
if association
- key_ids = calculated_data.collect { |row| row[group_alias] }
+ key_ids = calculated_data.collect { |row| row[group_aliases.first] }
key_records = association.klass.base_class.find(key_ids)
key_records = Hash[key_records.map { |r| [r.id, r] }]
end
ActiveSupport::OrderedHash[calculated_data.map do |row|
- key = type_cast_calculated_value(row[group_alias], group_column)
+ key = group_columns.map { |aliaz, column|
+ type_cast_calculated_value(row[aliaz], column)
+ }
+ key = key.first if key.size == 1
key = key_records[key] if associated
[key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
end]
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index e9e9c85122..4192456447 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -300,7 +300,7 @@ module ActiveRecord
unless record
conditions = arel.where_sql
conditions = " [#{conditions}]" if conditions
- raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}"
+ raise RecordNotFound, "Couldn't find #{@klass.name} with #{@klass.primary_key}=#{id}#{conditions}"
end
record
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index c5428dccd6..32c7d08daa 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -25,6 +25,11 @@ module ActiveRecord
attribute.in(values)
when Range, Arel::Relation
attribute.in(value)
+ when ActiveRecord::Base
+ attribute.eq(value.quoted_id)
+ when Class
+ # FIXME: I think we need to deprecate this behavior
+ attribute.eq(value.name)
else
attribute.eq(value)
end
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
index 3fc596e02a..ba99800fb2 100644
--- a/activerecord/lib/active_record/session_store.rb
+++ b/activerecord/lib/active_record/session_store.rb
@@ -228,7 +228,7 @@ module ActiveRecord
@session_id = attributes[:session_id]
@data = attributes[:data]
@marshaled_data = attributes[:marshaled_data]
- @new_record = @marshaled_data.nil?
+ @persisted = !@marshaled_data.nil?
end
# Lazy-unmarshal session state.
@@ -252,8 +252,8 @@ module ActiveRecord
marshaled_data = self.class.marshal(data)
connect = connection
- if @new_record
- @new_record = false
+ unless @persisted
+ @persisted = true
connect.update <<-end_sql, 'Create session'
INSERT INTO #{table_name} (
#{connect.quote_column_name(session_id_column)},
@@ -272,7 +272,7 @@ module ActiveRecord
end
def destroy
- return if @new_record
+ return unless @persisted
connect = connection
connect.delete <<-end_sql, 'Destroy session'
@@ -321,6 +321,7 @@ module ActiveRecord
if sid = current_session_id(env)
Base.silence do
get_session_model(env, sid).destroy
+ env[SESSION_RECORD_KEY] = nil
end
end
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index ab737f0f88..8c94d1a2bc 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -242,7 +242,7 @@ module ActiveRecord
with_transaction_returning_status { super }
end
- # Reset id and @new_record if the transaction rolls back.
+ # Reset id and @persisted if the transaction rolls back.
def rollback_active_record_state!
remember_transaction_record_state
yield
@@ -297,9 +297,9 @@ module ActiveRecord
# Save the new record state and id of a record so it can be restored later if a transaction fails.
def remember_transaction_record_state #:nodoc
@_start_transaction_state ||= {}
- unless @_start_transaction_state.include?(:new_record)
+ unless @_start_transaction_state.include?(:persisted)
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
- @_start_transaction_state[:new_record] = @new_record
+ @_start_transaction_state[:persisted] = @persisted
end
unless @_start_transaction_state.include?(:destroyed)
@_start_transaction_state[:destroyed] = @destroyed
@@ -323,7 +323,7 @@ module ActiveRecord
restore_state = remove_instance_variable(:@_start_transaction_state)
if restore_state
@attributes = @attributes.dup if @attributes.frozen?
- @new_record = restore_state[:new_record]
+ @persisted = restore_state[:persisted]
@destroyed = restore_state[:destroyed]
if restore_state[:id]
self.id = restore_state[:id]
@@ -345,11 +345,11 @@ module ActiveRecord
def transaction_include_action?(action) #:nodoc
case action
when :create
- transaction_record_state(:new_record)
+ transaction_record_state(:new_record) || !transaction_record_state(:persisted)
when :destroy
destroyed?
when :update
- !(transaction_record_state(:new_record) || destroyed?)
+ !(transaction_record_state(:new_record) || !transaction_record_state(:persisted) || destroyed?)
end
end
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index f367315b22..ee45fcdf35 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -51,7 +51,7 @@ module ActiveRecord
# Runs all the specified validations and returns true if no errors were added otherwise false.
def valid?(context = nil)
- context ||= (new_record? ? :create : :update)
+ context ||= (persisted? ? :update : :create)
output = super(context)
errors.empty? && output
end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index a25558bd80..3eba7510ac 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -31,7 +31,7 @@ module ActiveRecord
relation = relation.where(scope_item => scope_value)
end
- unless record.new_record?
+ if record.persisted?
# TODO : This should be in Arel
relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
end
diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb
index 89eba15be1..0667be7d23 100644
--- a/activerecord/lib/active_record/version.rb
+++ b/activerecord/lib/active_record/version.rb
@@ -3,8 +3,8 @@ module ActiveRecord
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 0fa4328826..1b0c00bd5a 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -285,10 +285,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm = firm
- assert final_cut.new_record?
+ assert !final_cut.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !firm.new_record?
+ assert final_cut.persisted?
+ assert firm.persisted?
assert_equal firm, final_cut.firm
assert_equal firm, final_cut.firm(true)
end
@@ -297,10 +297,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm_with_primary_key = firm
- assert final_cut.new_record?
+ assert !final_cut.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !firm.new_record?
+ assert final_cut.persisted?
+ assert firm.persisted?
assert_equal firm, final_cut.firm_with_primary_key
assert_equal firm, final_cut.firm_with_primary_key(true)
end
diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
index b124a2bfc3..fb59f63f91 100644
--- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
+++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
@@ -17,7 +17,7 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase
def generate_test_objects
post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 )
- tagging = Tagging.create( :taggable => post )
+ Tagging.create( :taggable => post )
end
def test_class_names
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index cae51ee211..10fb80f822 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -323,7 +323,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_through_a_belongs_to_association
author = authors(:mary)
- post = Post.create!(:author => author, :title => "TITLE", :body => "BODY")
+ Post.create!(:author => author, :title => "TITLE", :body => "BODY")
author.author_favorites.create(:favorite_author_id => 1)
author.author_favorites.create(:favorite_author_id => 2)
posts_with_author_favorites = author.posts.find(:all, :include => :author_favorites)
@@ -521,7 +521,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_inheritance
- posts = SpecialPost.find(:all, :include => [ :comments ])
+ SpecialPost.find(:all, :include => [ :comments ])
end
def test_eager_has_one_with_association_inheritance
@@ -561,16 +561,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_invalid_association_reference
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=> :monkeys )
+ Post.find(6, :include=> :monkeys )
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=>[ :monkeys ])
+ Post.find(6, :include=>[ :monkeys ])
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=>[ 'monkeys' ])
+ Post.find(6, :include=>[ 'monkeys' ])
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
- post = Post.find(6, :include=>[ :monkeys, :elephants ])
+ Post.find(6, :include=>[ :monkeys, :elephants ])
}
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index c6777d0cb3..513f76255c 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -251,10 +251,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
no_of_projects = Project.count
aredridel = Developer.new("name" => "Aredridel")
aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")])
- assert aredridel.new_record?
- assert p.new_record?
+ assert !aredridel.persisted?
+ assert !p.persisted?
assert aredridel.save
- assert !aredridel.new_record?
+ assert aredridel.persisted?
assert_equal no_of_devels+1, Developer.count
assert_equal no_of_projects+1, Project.count
assert_equal 2, aredridel.projects.size
@@ -288,22 +288,22 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal devel.projects.last, proj
assert devel.projects.loaded?
- assert proj.new_record?
+ assert !proj.persisted?
devel.save
- assert !proj.new_record?
+ assert proj.persisted?
assert_equal devel.projects.last, proj
assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
end
def test_build_by_new_record
devel = Developer.new(:name => "Marcel", :salary => 75000)
- proj1 = devel.projects.build(:name => "Make bed")
+ devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
assert_equal devel.projects.last, proj2
- assert proj2.new_record?
+ assert !proj2.persisted?
devel.save
- assert !devel.new_record?
- assert !proj2.new_record?
+ assert devel.persisted?
+ assert proj2.persisted?
assert_equal devel.projects.last, proj2
assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
end
@@ -316,19 +316,19 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal devel.projects.last, proj
assert !devel.projects.loaded?
- assert !proj.new_record?
+ assert proj.persisted?
assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
end
def test_create_by_new_record
devel = Developer.new(:name => "Marcel", :salary => 75000)
- proj1 = devel.projects.build(:name => "Make bed")
+ devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
assert_equal devel.projects.last, proj2
- assert proj2.new_record?
+ assert !proj2.persisted?
devel.save
- assert !devel.new_record?
- assert !proj2.new_record?
+ assert devel.persisted?
+ assert proj2.persisted?
assert_equal devel.projects.last, proj2
assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
end
@@ -343,7 +343,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
# in Oracle '' is saved as null therefore need to save ' ' in not null column
another_post = categories(:general).post_with_conditions.create(:body => ' ')
- assert !another_post.new_record?
+ assert another_post.persisted?
assert_equal 'Yet Another Testing Title', another_post.title
end
@@ -559,8 +559,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_dynamic_find_should_respect_association_order
# Developers are ordered 'name DESC, id DESC'
- low_id_jamis = developers(:jamis)
- middle_id_jamis = developers(:poor_jamis)
high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
assert_equal high_id_jamis, projects(:active_record).developers.find(:first, :conditions => "name = 'Jamis'")
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index c9f00fd737..33c53e695b 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -66,6 +66,17 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 'exotic', bulb.name
end
+ def test_no_sql_should_be_fired_if_association_already_loaded
+ car = Car.create(:name => 'honda')
+ bulb = car.bulbs.create
+ bulbs = Car.first.bulbs
+ bulbs.inspect # to load all instances of bulbs
+ assert_no_queries do
+ bulbs.first()
+ bulbs.first({})
+ end
+ end
+
def test_create_resets_cached_counters
person = Person.create!(:first_name => 'tenderlove')
post = Post.first
@@ -73,7 +84,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
- reader = person.readers.create(:post_id => post.id)
+ person.readers.create(:post_id => post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
@@ -88,7 +99,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
- reader = person.readers.find_or_create_by_post_id(post.id)
+ person.readers.find_or_create_by_post_id(post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
@@ -187,7 +198,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
another = author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body")
assert_equal number_of_posts + 1, Post.count
assert_equal another, author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body")
- assert !another.new_record?
+ assert another.persisted?
end
def test_cant_save_has_many_readonly_association
@@ -402,7 +413,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_adding_using_create
first_firm = companies(:first_firm)
assert_equal 2, first_firm.plain_clients.size
- natural = first_firm.plain_clients.create(:name => "Natural Company")
+ first_firm.plain_clients.create(:name => "Natural Company")
assert_equal 3, first_firm.plain_clients.length
assert_equal 3, first_firm.plain_clients.size
end
@@ -453,7 +464,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
@@ -483,7 +494,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_build_followed_by_save_does_not_load_target
- new_client = companies(:first_firm).clients_of_firm.build("name" => "Another Client")
+ companies(:first_firm).clients_of_firm.build("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
@@ -508,7 +519,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
@@ -543,7 +554,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_create
force_signal37_to_load_all_clients_of_firm
new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal new_client, companies(:first_firm).clients_of_firm.last
assert_equal new_client, companies(:first_firm).clients_of_firm(true).last
end
@@ -554,7 +565,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_create_followed_by_save_does_not_load_target
- new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
@@ -563,7 +574,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
the_client = companies(:first_firm).clients.find_or_initialize_by_name("Yet another client")
assert_equal companies(:first_firm).id, the_client.firm_id
assert_equal "Yet another client", the_client.name
- assert the_client.new_record?
+ assert !the_client.persisted?
end
def test_find_or_create_updates_size
@@ -752,7 +763,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
- assert !another_ms_client.new_record?
+ assert another_ms_client.persisted?
assert_equal 'Microsoft', another_ms_client.name
end
@@ -852,7 +863,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_dependence_for_associations_with_hash_condition
david = authors(:david)
- post = posts(:thinking).id
assert_difference('Post.count', -1) { assert david.destroy }
end
@@ -872,7 +882,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_three_levels_of_dependence
topic = Topic.create "title" => "neat and simple"
reply = topic.replies.create "title" => "neat and simple", "content" => "still digging it"
- silly_reply = reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
+ reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
assert_nothing_raised { topic.destroy }
end
@@ -897,7 +907,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_depends_and_nullify
num_accounts = Account.count
- num_companies = Company.count
core = companies(:rails_core)
assert_equal accounts(:rails_core_account), core.account
@@ -914,7 +923,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_restrict
firm = RestrictedFirm.new(:name => 'restrict')
firm.save!
- child_firm = firm.companies.create(:name => 'child')
+ firm.companies.create(:name => 'child')
assert !firm.companies.empty?
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
end
@@ -1273,4 +1282,25 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
comment = post.comments.build
assert post.comments.include?(comment)
end
+
+ def test_load_target_respects_protected_attributes
+ topic = Topic.create!
+ reply = topic.replies.create(:title => "reply 1")
+ reply.approved = false
+ reply.save!
+
+ # Save with a different object instance, so the instance that's still held
+ # in topic.relies doesn't know about the changed attribute.
+ reply2 = Reply.find(reply.id)
+ reply2.approved = true
+ reply2.save!
+
+ # Force loading the collection from the db. This will merge the existing
+ # object (reply) with what gets loaded from the db (which includes the
+ # changed approved attribute). approved is a protected attribute, so if mass
+ # assignment is used, it won't get updated and will still be false.
+ first = topic.replies.to_a.first
+ assert_equal reply.id, first.id
+ assert_equal true, first.approved?
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 4e398751d2..7c3d20e8bd 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -472,4 +472,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
authors = Author.joins(:essay_categories_2).where('categories.id' => categories(:general).id)
assert_equal authors(:david), authors.first
end
+
+ def test_size_of_through_association_should_increase_correctly_when_has_many_association_is_added
+ post = posts(:thinking)
+ readers = post.readers.size
+ post.people << people(:michael)
+ assert_equal readers + 1, post.readers.size
+ end
end
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index b522be3fe0..6fbeff8aa9 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -268,7 +268,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_assignment_before_child_saved
firm = Firm.find(1)
firm.account = a = Account.new("credit_limit" => 1000)
- assert !a.new_record?
+ assert a.persisted?
assert_equal a, firm.account
assert_equal a, firm.account
assert_equal a, firm.account(true)
@@ -323,7 +323,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_create_respects_hash_condition
account = companies(:first_firm).create_account_limit_500_with_hash_conditions
- assert !account.new_record?
+ assert account.persisted?
assert_equal 500, account.credit_limit
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index fa5c2e49df..081583038f 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -551,8 +551,8 @@ class InverseMultipleHasManyInversesForSameModel < ActiveRecord::TestCase
def test_that_we_can_load_associations_that_have_the_same_reciprocal_name_from_different_models
assert_nothing_raised(ActiveRecord::AssociationTypeMismatch) do
i = Interest.find(:first)
- z = i.zine
- m = i.man
+ i.zine
+ i.man
end
end
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 385505b109..217d06f3d9 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -442,11 +442,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_tag = Tag.new(:name => "new")
saved_post.tags << new_tag
- assert !new_tag.new_record? #consistent with habtm!
- assert !saved_post.new_record?
+ assert new_tag.persisted? #consistent with habtm!
+ assert saved_post.persisted?
assert saved_post.tags.include?(new_tag)
- assert !new_tag.new_record?
+ assert new_tag.persisted?
assert saved_post.reload.tags(true).include?(new_tag)
@@ -454,16 +454,16 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
saved_tag = tags(:general)
new_post.tags << saved_tag
- assert new_post.new_record?
- assert !saved_tag.new_record?
+ assert !new_post.persisted?
+ assert saved_tag.persisted?
assert new_post.tags.include?(saved_tag)
new_post.save!
- assert !new_post.new_record?
+ assert new_post.persisted?
assert new_post.reload.tags(true).include?(saved_tag)
- assert posts(:thinking).tags.build.new_record?
- assert posts(:thinking).tags.new.new_record?
+ assert !posts(:thinking).tags.build.persisted?
+ assert !posts(:thinking).tags.new.persisted?
end
def test_create_associate_when_adding_to_has_many_through
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index dd8152b219..93a51d3606 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -120,7 +120,7 @@ class AssociationsTest < ActiveRecord::TestCase
def test_force_reload_is_uncached
firm = Firm.create!("name" => "A New Firm, Inc")
- client = Client.create!("name" => "TheClient.com", :firm => firm)
+ Client.create!("name" => "TheClient.com", :firm => firm)
ActiveRecord::Base.cache do
firm.clients.each {}
assert_queries(0) { assert_not_nil firm.clients.each {} }
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index ab9a65944f..bb0166a60c 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -568,7 +568,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def test_bulk_update_respects_access_control
privatize("title=(value)")
- assert_raise(ActiveRecord::UnknownAttributeError) { topic = @target.new(:title => "Rants about pants") }
+ assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(:title => "Rants about pants") }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } }
end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 89be94c81f..b13cb2d7a2 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -83,7 +83,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
assert !firm.build_account_using_primary_key.valid?
assert firm.save
- assert firm.account_using_primary_key.new_record?
+ assert !firm.account_using_primary_key.persisted?
end
def test_save_fails_for_invalid_has_one
@@ -114,10 +114,10 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
account = firm.account.build("credit_limit" => 1000)
assert_equal account, firm.account
- assert account.new_record?
+ assert !account.persisted?
assert firm.save
assert_equal account, firm.account
- assert !account.new_record?
+ assert account.persisted?
end
def test_build_before_either_saved
@@ -125,16 +125,16 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm.account = account = Account.new("credit_limit" => 1000)
assert_equal account, firm.account
- assert account.new_record?
+ assert !account.persisted?
assert firm.save
assert_equal account, firm.account
- assert !account.new_record?
+ assert account.persisted?
end
def test_assignment_before_parent_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.find(1)
- assert firm.new_record?
+ assert !firm.persisted?
assert_equal a, firm.account
assert firm.save
assert_equal a, firm.account
@@ -144,12 +144,12 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
def test_assignment_before_either_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.new("credit_limit" => 1000)
- assert firm.new_record?
- assert a.new_record?
+ assert !firm.persisted?
+ assert !a.persisted?
assert_equal a, firm.account
assert firm.save
- assert !firm.new_record?
- assert !a.new_record?
+ assert firm.persisted?
+ assert a.persisted?
assert_equal a, firm.account
assert_equal a, firm.account(true)
end
@@ -203,7 +203,7 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert !client.firm.valid?
assert client.save
- assert client.firm.new_record?
+ assert !client.firm.persisted?
end
def test_save_fails_for_invalid_belongs_to
@@ -232,10 +232,10 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
apple = Firm.new("name" => "Apple")
client.firm = apple
assert_equal apple, client.firm
- assert apple.new_record?
+ assert !apple.persisted?
assert client.save
assert apple.save
- assert !apple.new_record?
+ assert apple.persisted?
assert_equal apple, client.firm
assert_equal apple, client.firm(true)
end
@@ -244,11 +244,11 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
final_cut = Client.new("name" => "Final Cut")
apple = Firm.new("name" => "Apple")
final_cut.firm = apple
- assert final_cut.new_record?
- assert apple.new_record?
+ assert !final_cut.persisted?
+ assert !apple.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !apple.new_record?
+ assert final_cut.persisted?
+ assert apple.persisted?
assert_equal apple, final_cut.firm
assert_equal apple, final_cut.firm(true)
end
@@ -348,23 +348,21 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
def test_invalid_adding
firm = Firm.find(1)
assert !(firm.clients_of_firm << c = Client.new)
- assert c.new_record?
+ assert !c.persisted?
assert !firm.valid?
assert !firm.save
- assert c.new_record?
+ assert !c.persisted?
end
def test_invalid_adding_before_save
- no_of_firms = Firm.count
- no_of_clients = Client.count
new_firm = Firm.new("name" => "A New Firm, Inc")
new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
- assert c.new_record?
+ assert !c.persisted?
assert !c.valid?
assert !new_firm.valid?
assert !new_firm.save
- assert c.new_record?
- assert new_firm.new_record?
+ assert !c.persisted?
+ assert !new_firm.persisted?
end
def test_invalid_adding_with_validate_false
@@ -375,7 +373,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert firm.valid?
assert !client.valid?
assert firm.save
- assert client.new_record?
+ assert !client.persisted?
end
def test_valid_adding_with_validate_false
@@ -386,22 +384,22 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert firm.valid?
assert client.valid?
- assert client.new_record?
+ assert !client.persisted?
firm.unvalidated_clients_of_firm << client
assert firm.save
- assert !client.new_record?
+ assert client.persisted?
assert_equal no_of_clients + 1, Client.count
end
def test_invalid_build
new_client = companies(:first_firm).clients_of_firm.build
- assert new_client.new_record?
+ assert !new_client.persisted?
assert !new_client.valid?
assert_equal new_client, companies(:first_firm).clients_of_firm.last
assert !companies(:first_firm).save
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal 1, companies(:first_firm).clients_of_firm(true).size
end
@@ -420,8 +418,8 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert_equal no_of_firms, Firm.count # Firm was not saved to database.
assert_equal no_of_clients, Client.count # Clients were not saved to database.
assert new_firm.save
- assert !new_firm.new_record?
- assert !c.new_record?
+ assert new_firm.persisted?
+ assert c.persisted?
assert_equal new_firm, c.firm
assert_equal no_of_firms + 1, Firm.count # Firm was saved to database.
assert_equal no_of_clients + 2, Client.count # Clients were saved to database.
@@ -455,13 +453,13 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
company.name += '-changed'
assert_queries(2) { assert company.save }
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_before_save
company = companies(:first_firm)
- new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+ assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
company.name += '-changed'
assert_queries(3) { assert company.save }
@@ -475,13 +473,13 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
company.name += '-changed'
assert_queries(2) { assert company.save }
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_via_block_before_save
company = companies(:first_firm)
- new_clients = assert_no_queries do
+ assert_no_queries do
company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
client.name = "changed"
end
@@ -507,62 +505,62 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
new_account = Account.new("credit_limit" => 1000)
new_firm = Firm.new("name" => "some firm")
- assert new_firm.new_record?
+ assert !new_firm.persisted?
new_account.firm = new_firm
new_account.save!
- assert !new_firm.new_record?
+ assert new_firm.persisted?
new_account = Account.new("credit_limit" => 1000)
new_autosaved_firm = Firm.new("name" => "some firm")
- assert new_autosaved_firm.new_record?
+ assert !new_autosaved_firm.persisted?
new_account.unautosaved_firm = new_autosaved_firm
new_account.save!
- assert new_autosaved_firm.new_record?
+ assert !new_autosaved_firm.persisted?
end
def test_autosave_new_record_on_has_one_can_be_disabled_per_relationship
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.account = account
firm.save!
- assert !account.new_record?
+ assert account.persisted?
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
firm.unautosaved_account = account
- assert account.new_record?
+ assert !account.persisted?
firm.unautosaved_account = account
firm.save!
- assert account.new_record?
+ assert !account.persisted?
end
def test_autosave_new_record_on_has_many_can_be_disabled_per_relationship
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.accounts << account
firm.save!
- assert !account.new_record?
+ assert account.persisted?
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.unautosaved_accounts << account
firm.save!
- assert account.new_record?
+ assert !account.persisted?
end
end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index ceb1272862..26f388ca46 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -182,7 +182,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_initialize_with_invalid_attribute
begin
- topic = Topic.new({ "title" => "test",
+ Topic.new({ "title" => "test",
"last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
rescue ActiveRecord::MultiparameterAssignmentErrors => ex
assert_equal(1, ex.errors.size)
@@ -397,6 +397,15 @@ class BasicsTest < ActiveRecord::TestCase
assert_not_equal Topic.new, Topic.new
end
+ def test_equality_of_destroyed_records
+ topic_1 = Topic.new(:title => 'test_1')
+ topic_1.save
+ topic_2 = Topic.find(topic_1.id)
+ topic_1.destroy
+ assert_equal topic_1, topic_2
+ assert_equal topic_2, topic_1
+ end
+
def test_hashing
assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
end
@@ -656,8 +665,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_new_record_returns_boolean
- assert_equal true, Topic.new.new_record?
- assert_equal false, Topic.find(1).new_record?
+ assert_equal false, Topic.new.persisted?
+ assert_equal true, Topic.find(1).persisted?
end
def test_clone
@@ -665,7 +674,7 @@ class BasicsTest < ActiveRecord::TestCase
cloned_topic = nil
assert_nothing_raised { cloned_topic = topic.clone }
assert_equal topic.title, cloned_topic.title
- assert cloned_topic.new_record?
+ assert !cloned_topic.persisted?
# test if the attributes have been cloned
topic.title = "a"
@@ -684,7 +693,7 @@ class BasicsTest < ActiveRecord::TestCase
# test if saved clone object differs from original
cloned_topic.save
- assert !cloned_topic.new_record?
+ assert cloned_topic.persisted?
assert_not_equal cloned_topic.id, topic.id
cloned_topic.reload
@@ -700,7 +709,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_nothing_raised { clone = dev.clone }
assert_kind_of DeveloperSalary, clone.salary
assert_equal dev.salary.amount, clone.salary.amount
- assert clone.new_record?
+ assert !clone.persisted?
# test if the attributes have been cloned
original_amount = clone.salary.amount
@@ -708,7 +717,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal original_amount, clone.salary.amount
assert clone.save
- assert !clone.new_record?
+ assert clone.persisted?
assert_not_equal clone.id, dev.id
end
@@ -963,7 +972,6 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_nil_serialized_attribute_with_class_constraint
- myobj = MyObject.new('value1', 'value2')
topic = Topic.new
assert_nil topic.content
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 61fbf01a50..5cb8485b4b 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -54,6 +54,19 @@ class CalculationsTest < ActiveRecord::TestCase
c = Account.sum(:credit_limit, :group => :firm_id)
[1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
end
+
+ def test_should_group_by_multiple_fields
+ c = Account.count(:all, :group => ['firm_id', :credit_limit])
+ [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
+ end
+
+ def test_should_group_by_multiple_fields_having_functions
+ c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
+ assert_equal 1, c[["Carl", "The Third Topic of the day"]]
+ assert_equal 1, c[["Mary", "Reply"]]
+ assert_equal 1, c[["David", "The First Topic"]]
+ assert_equal 1, c[["Carl", "Reply"]]
+ end
def test_should_group_by_summed_field
c = Account.sum(:credit_limit, :group => :firm_id)
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 4c9475f1cd..f4af6506c5 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -10,6 +10,7 @@ require 'models/entrant'
require 'models/project'
require 'models/developer'
require 'models/customer'
+require 'models/toy'
class FinderTest < ActiveRecord::TestCase
fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers, :categories, :categorizations
@@ -728,7 +729,7 @@ class FinderTest < ActiveRecord::TestCase
sig38 = Company.find_or_create_by_name("38signals")
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name("38signals")
- assert !sig38.new_record?
+ assert sig38.persisted?
end
def test_find_or_create_from_two_attributes
@@ -736,7 +737,7 @@ class FinderTest < ActiveRecord::TestCase
another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
assert_equal number_of_topics + 1, Topic.count
assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
- assert !another.new_record?
+ assert another.persisted?
end
def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
@@ -744,7 +745,7 @@ class FinderTest < ActiveRecord::TestCase
created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth")
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth")
- assert !created_customer.new_record?
+ assert created_customer.persisted?
end
def test_find_or_create_from_one_attribute_and_hash
@@ -752,7 +753,7 @@ class FinderTest < ActiveRecord::TestCase
sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
- assert !sig38.new_record?
+ assert sig38.persisted?
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
@@ -763,7 +764,7 @@ class FinderTest < ActiveRecord::TestCase
created_customer = Customer.find_or_create_by_balance(Money.new(123))
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123))
- assert !created_customer.new_record?
+ assert created_customer.persisted?
end
def test_find_or_create_from_one_aggregate_attribute_and_hash
@@ -773,7 +774,7 @@ class FinderTest < ActiveRecord::TestCase
created_customer = Customer.find_or_create_by_balance({:balance => balance, :name => name})
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance({:balance => balance, :name => name})
- assert !created_customer.new_record?
+ assert created_customer.persisted?
assert_equal balance, created_customer.balance
assert_equal name, created_customer.name
end
@@ -781,13 +782,13 @@ class FinderTest < ActiveRecord::TestCase
def test_find_or_initialize_from_one_attribute
sig38 = Company.find_or_initialize_by_name("38signals")
assert_equal "38signals", sig38.name
- assert sig38.new_record?
+ assert !sig38.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute
new_customer = Customer.find_or_initialize_by_balance(Money.new(123))
assert_equal 123, new_customer.balance.amount
- assert new_customer.new_record?
+ assert !new_customer.persisted?
end
def test_find_or_initialize_from_one_attribute_should_not_set_attribute_even_when_protected
@@ -795,7 +796,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_not_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_not_set_attribute_even_when_protected
@@ -803,7 +804,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_not_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected
@@ -811,7 +812,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected
@@ -819,7 +820,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected_and_also_set_the_hash
@@ -827,7 +828,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected_and_also_set_the_hash
@@ -835,7 +836,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_should_set_protected_attributes_if_given_as_block
@@ -843,7 +844,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_should_set_protected_attributes_if_given_as_block
@@ -851,7 +852,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_create_should_work_with_block_on_first_call
@@ -862,21 +863,21 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_two_attributes
another = Topic.find_or_initialize_by_title_and_author_name("Another topic","John")
assert_equal "Another topic", another.title
assert_equal "John", another.author_name
- assert another.new_record?
+ assert !another.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute_and_one_not
new_customer = Customer.find_or_initialize_by_balance_and_name(Money.new(123), "Elizabeth")
assert_equal 123, new_customer.balance.amount
assert_equal "Elizabeth", new_customer.name
- assert new_customer.new_record?
+ assert !new_customer.persisted?
end
def test_find_or_initialize_from_one_attribute_and_hash
@@ -884,7 +885,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
- assert sig38.new_record?
+ assert !sig38.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute_and_hash
@@ -893,7 +894,7 @@ class FinderTest < ActiveRecord::TestCase
new_customer = Customer.find_or_initialize_by_balance({:balance => balance, :name => name})
assert_equal balance, new_customer.balance
assert_equal name, new_customer.name
- assert new_customer.new_record?
+ assert !new_customer.persisted?
end
def test_find_with_bad_sql
@@ -950,7 +951,7 @@ class FinderTest < ActiveRecord::TestCase
# http://dev.rubyonrails.org/ticket/6778
def test_find_ignores_previously_inserted_record
- post = Post.create!(:title => 'test', :body => 'it out')
+ Post.create!(:title => 'test', :body => 'it out')
assert_equal [], Post.find_all_by_id(nil)
end
@@ -1012,6 +1013,15 @@ class FinderTest < ActiveRecord::TestCase
end
end
+ def test_find_one_message_with_custom_primary_key
+ Toy.set_primary_key :name
+ begin
+ Toy.find 'Hello World!'
+ rescue ActiveRecord::RecordNotFound => e
+ assert_equal 'Couldn\'t find Toy with name=Hello World!', e.message
+ end
+ end
+
protected
def bind(statement, *vars)
if vars.first.is_a?(Hash)
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index d5ef30e137..9ce163a00f 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -58,7 +58,7 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_inserts
- topics = create_fixtures("topics")
+ create_fixtures("topics")
first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'")
assert_equal("The First Topic", first_row["title"])
@@ -114,7 +114,7 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_insert_with_datetime
- topics = create_fixtures("tasks")
+ create_fixtures("tasks")
first = Task.find(1)
assert first
end
@@ -240,7 +240,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!)
def test_create_fixtures_resets_sequences_when_not_cached
@instances.each do |instance|
- max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (name, fixture)|
+ max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (_, fixture)|
fixture_id = fixture['id'].to_i
fixture_id > _max_id ? fixture_id : _max_id
end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index e6eef805cf..ab9b35172b 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -1947,7 +1947,7 @@ if ActiveRecord::Base.connection.supports_migrations?
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
- Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
@@ -1972,7 +1972,7 @@ if ActiveRecord::Base.connection.supports_migrations?
sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2"
- Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, sources)
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
@@ -1992,7 +1992,7 @@ if ActiveRecord::Base.connection.supports_migrations?
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
- Time.travel_to(created_at = Time.utc(2010, 2, 20, 10, 10, 10)) do
+ Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do
ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.rb")
assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.rb")
@@ -2024,11 +2024,26 @@ if ActiveRecord::Base.connection.supports_migrations?
clear
end
+ def test_copying_migrations_to_non_existing_directory
+ @migrations_path = MIGRATIONS_ROOT + "/non_existing"
+ @existing_migrations = []
+
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ assert_equal 2, copied.length
+ end
+ ensure
+ clear
+ Dir.delete(@migrations_path)
+ end
+
def test_copying_migrations_to_empty_directory
@migrations_path = MIGRATIONS_ROOT + "/empty"
@existing_migrations = []
- Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index fb24c65fff..6ac3e3fc56 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -122,7 +122,7 @@ class NamedScopeTest < ActiveRecord::TestCase
:joins => 'JOIN authors ON authors.id = posts.author_id',
:conditions => [ 'authors.author_address_id = ?', address.id ]
)
- assert_equal posts_with_authors_at_address_titles, Post.with_authors_at_address(address).find(:all, :select => 'title')
+ assert_equal posts_with_authors_at_address_titles.map(&:title), Post.with_authors_at_address(address).find(:all, :select => 'title').map(&:title)
end
def test_scope_with_object
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 60f89da95e..92af53d56f 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -139,6 +139,14 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
assert_equal 'gardening', interest.reload.topic
end
+ def test_reject_if_with_blank_nested_attributes_id
+ # When using a select list to choose an existing 'ship' id, with :include_blank => true
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| attributes[:id].blank? }
+
+ pirate = Pirate.new(:catchphrase => "Stop wastin' me time")
+ pirate.ship_attributes = { :id => "" }
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { pirate.save! }
+ end
end
class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@@ -163,7 +171,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@ship.destroy
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert @pirate.ship.new_record?
+ assert !@pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
@@ -184,7 +192,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_replace_an_existing_record_if_there_is_no_id
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert @pirate.ship.new_record?
+ assert !@pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
assert_equal 'Nights Dirty Lightning', @ship.name
end
@@ -256,7 +264,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_also_work_with_a_HashWithIndifferentAccess
@pirate.ship_attributes = HashWithIndifferentAccess.new(:id => @ship.id, :name => 'Davy Jones Gold Dagger')
- assert !@pirate.ship.new_record?
+ assert @pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
@@ -348,7 +356,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@pirate.destroy
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
- assert @ship.pirate.new_record?
+ assert !@ship.pirate.persisted?
assert_equal 'Arr', @ship.pirate.catchphrase
end
@@ -369,7 +377,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_replace_an_existing_record_if_there_is_no_id
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
- assert @ship.pirate.new_record?
+ assert !@ship.pirate.persisted?
assert_equal 'Arr', @ship.pirate.catchphrase
assert_equal 'Aye', @pirate.catchphrase
end
@@ -458,7 +466,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@pirate.delete
@ship.reload.attributes = { :update_only_pirate_attributes => { :catchphrase => 'Arr' } }
- assert @ship.update_only_pirate.new_record?
+ assert !@ship.update_only_pirate.persisted?
end
def test_should_update_existing_when_update_only_is_true_and_no_id_is_given
@@ -596,10 +604,10 @@ module NestedAttributesOnACollectionAssociationTests
association_getter => { 'foo' => { :name => 'Grace OMalley' }, 'bar' => { :name => 'Privateers Greed' }}
}
- assert @pirate.send(@association_name).first.new_record?
+ assert !@pirate.send(@association_name).first.persisted?
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
- assert @pirate.send(@association_name).last.new_record?
+ assert !@pirate.send(@association_name).last.persisted?
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index ffe6fb95b8..8ca9d626d1 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -192,7 +192,6 @@ class PersistencesTest < ActiveRecord::TestCase
topic = Topic.create("title" => "New Topic") do |t|
t.author_name = "David"
end
- topicReloaded = Topic.find(topic.id)
assert_equal("New Topic", topic.title)
assert_equal("David", topic.author_name)
end
@@ -241,6 +240,15 @@ class PersistencesTest < ActiveRecord::TestCase
assert_nothing_raised { minimalistic.save }
end
+ def test_update_sti_type
+ assert_instance_of Reply, topics(:second)
+
+ topic = topics(:second).becomes(Topic)
+ assert_instance_of Topic, topic
+ topic.save!
+ assert_instance_of Topic, Topic.find(topic.id)
+ end
+
def test_delete
topic = Topic.find(1)
assert_equal topic, topic.delete, 'topic.delete did not return self'
@@ -261,7 +269,7 @@ class PersistencesTest < ActiveRecord::TestCase
end
def test_record_not_found_exception
- assert_raise(ActiveRecord::RecordNotFound) { topicReloaded = Topic.find(99999) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
end
def test_update_all
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index 5bb21a54bd..33916c4e46 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -133,7 +133,6 @@ class QueryCacheExpiryTest < ActiveRecord::TestCase
def test_cache_is_expired_by_habtm_delete
ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
ActiveRecord::Base.cache do
- c = Category.find(1)
p = Post.find(1)
assert p.categories.any?
p.categories.delete_all
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index bf41199b77..77d56fc058 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -254,13 +254,11 @@ class HasManyScopingTest< ActiveRecord::TestCase
end
def test_should_maintain_default_scope_on_associations
- person = people(:michael)
magician = BadReference.find(1)
assert_equal [magician], people(:michael).bad_references
end
def test_should_default_scope_on_associations_is_overriden_by_association_conditions
- person = people(:michael)
assert_equal [], people(:michael).fixed_bad_references
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index f9385ab40f..7de7b95fa8 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -383,7 +383,7 @@ class RelationTest < ActiveRecord::TestCase
lifo = authors.find_or_initialize_by_name('Lifo')
assert_equal "Lifo", lifo.name
- assert lifo.new_record?
+ assert !lifo.persisted?
assert_equal authors(:david), authors.find_or_initialize_by_name(:name => 'David')
end
@@ -393,7 +393,7 @@ class RelationTest < ActiveRecord::TestCase
lifo = authors.find_or_create_by_name('Lifo')
assert_equal "Lifo", lifo.name
- assert ! lifo.new_record?
+ assert lifo.persisted?
assert_equal authors(:david), authors.find_or_create_by_name(:name => 'David')
end
@@ -426,6 +426,31 @@ class RelationTest < ActiveRecord::TestCase
assert_blank authors.all
end
+ def test_where_with_ar_object
+ author = Author.first
+ authors = Author.scoped.where(:id => author)
+ assert_equal 1, authors.all.length
+ end
+
+ def test_find_with_list_of_ar
+ author = Author.first
+ authors = Author.find([author])
+ assert_equal author, authors.first
+ end
+
+ class Mary < Author; end
+
+ def test_find_by_classname
+ Author.create!(:name => Mary.name)
+ assert_equal 1, Author.where(:name => Mary).size
+ end
+
+ def test_find_by_id_with_list_of_ar
+ author = Author.first
+ authors = Author.find_by_id([author])
+ assert_equal author, authors
+ end
+
def test_exists
davids = Author.where(:name => 'David')
assert davids.exists?
@@ -627,10 +652,10 @@ class RelationTest < ActiveRecord::TestCase
sparrow = birds.create
assert_kind_of Bird, sparrow
- assert sparrow.new_record?
+ assert !sparrow.persisted?
hen = birds.where(:name => 'hen').create
- assert ! hen.new_record?
+ assert hen.persisted?
assert_equal 'hen', hen.name
end
@@ -641,7 +666,7 @@ class RelationTest < ActiveRecord::TestCase
hen = birds.where(:name => 'hen').create!
assert_kind_of Bird, hen
- assert ! hen.new_record?
+ assert hen.persisted?
assert_equal 'hen', hen.name
end
diff --git a/activerecord/test/cases/session_store/sql_bypass.rb b/activerecord/test/cases/session_store/sql_bypass.rb
index f0ba166465..7402b2afd6 100644
--- a/activerecord/test/cases/session_store/sql_bypass.rb
+++ b/activerecord/test/cases/session_store/sql_bypass.rb
@@ -18,9 +18,9 @@ module ActiveRecord
assert !Session.table_exists?
end
- def test_new_record?
+ def test_persisted?
s = SqlBypass.new :data => 'foo', :session_id => 10
- assert s.new_record?, 'this is a new record!'
+ assert !s.persisted?, 'this is a new record!'
end
def test_not_loaded?
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index eb93761fb2..70c098bc6d 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -113,7 +113,7 @@ class TimestampTest < ActiveRecord::TestCase
pet = Pet.first
owner = pet.owner
- owner.update_attribute(:happy_at, (time = 3.days.ago))
+ owner.update_attribute(:happy_at, 3.days.ago)
previously_owner_updated_at = owner.updated_at
pet.name = "I'm a parrot"
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 0fbcef4091..b0ccd71836 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -163,7 +163,7 @@ class TransactionTest < ActiveRecord::TestCase
@first.author_name += '_this_should_not_end_up_in_the_db'
@first.save!
flunk
- rescue => e
+ rescue
assert_equal original_author_name, @first.reload.author_name
assert_equal nbooks_before_save, Book.count
ensure
@@ -182,7 +182,7 @@ class TransactionTest < ActiveRecord::TestCase
:bonus_time => "2005-01-30t15:28:00.00+01:00",
:content => "Have a nice day",
:approved => false)
- new_record_snapshot = new_topic.new_record?
+ new_record_snapshot = !new_topic.persisted?
id_present = new_topic.has_attribute?(Topic.primary_key)
id_snapshot = new_topic.id
@@ -195,7 +195,7 @@ class TransactionTest < ActiveRecord::TestCase
flunk
rescue => e
assert_equal "Make the transaction rollback", e.message
- assert_equal new_record_snapshot, new_topic.new_record?, "The topic should have its old new_record value"
+ assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
ensure
@@ -370,21 +370,21 @@ class TransactionTest < ActiveRecord::TestCase
assert topic_2.save
@first.save
@second.destroy
- assert_equal false, topic_1.new_record?
+ assert_equal true, topic_1.persisted?
assert_not_nil topic_1.id
- assert_equal false, topic_2.new_record?
+ assert_equal true, topic_2.persisted?
assert_not_nil topic_2.id
- assert_equal false, @first.new_record?
+ assert_equal true, @first.persisted?
assert_not_nil @first.id
assert_equal true, @second.destroyed?
raise ActiveRecord::Rollback
end
- assert_equal true, topic_1.new_record?
+ assert_equal false, topic_1.persisted?
assert_nil topic_1.id
- assert_equal true, topic_2.new_record?
+ assert_equal false, topic_2.persisted?
assert_nil topic_2.id
- assert_equal false, @first.new_record?
+ assert_equal true, @first.persisted?
assert_not_nil @first.id
assert_equal false, @second.destroyed?
end
diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb
index 1246dd4276..56e345990f 100644
--- a/activerecord/test/cases/validations/association_validation_test.rb
+++ b/activerecord/test/cases/validations/association_validation_test.rb
@@ -17,7 +17,7 @@ class AssociationValidationTest < ActiveRecord::TestCase
o = Owner.new('name' => 'nopets')
assert !o.save
assert o.errors[:pets].any?
- pet = o.pets.build('name' => 'apet')
+ o.pets.build('name' => 'apet')
assert o.valid?
end
@@ -27,7 +27,7 @@ class AssociationValidationTest < ActiveRecord::TestCase
assert !o.save
assert o.errors[:pets].any?
- pet = o.pets.build('name' => 'apet')
+ o.pets.build('name' => 'apet')
assert o.valid?
2.times { o.pets.build('name' => 'apet') }
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 9a863c25a8..679d67553b 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -60,7 +60,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validates_uniqueness_with_validates
Topic.validates :title, :uniqueness => true
- t = Topic.create!('title' => 'abc')
+ Topic.create!('title' => 'abc')
t2 = Topic.new('title' => 'abc')
assert !t2.valid?
@@ -201,7 +201,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer
Topic.validates_uniqueness_of(:title, :case_sensitve => true)
- t = Topic.create!('title' => 101)
+ Topic.create!('title' => 101)
t2 = Topic.new('title' => 101)
assert !t2.valid?
diff --git a/activerecord/test/models/eye.rb b/activerecord/test/models/eye.rb
index 77f17b578e..dc8ae2b3f6 100644
--- a/activerecord/test/models/eye.rb
+++ b/activerecord/test/models/eye.rb
@@ -17,7 +17,7 @@ class Eye < ActiveRecord::Base
after_save :trace_after_save2
def trace_after_create
- (@after_create_callbacks_stack ||= []) << iris.new_record?
+ (@after_create_callbacks_stack ||= []) << !iris.persisted?
end
alias trace_after_create2 trace_after_create
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index d89c8cf381..f2c45053e7 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -48,7 +48,7 @@ class Pirate < ActiveRecord::Base
end
def reject_empty_ships_on_create(attributes)
- attributes.delete('_reject_me_if_new').present? && new_record?
+ attributes.delete('_reject_me_if_new').present? && !persisted?
end
attr_accessor :cancel_save_from_callback
diff --git a/activerecord/test/models/subject.rb b/activerecord/test/models/subject.rb
index d4b8b91de8..8e28f8b86b 100644
--- a/activerecord/test/models/subject.rb
+++ b/activerecord/test/models/subject.rb
@@ -8,7 +8,7 @@ class Subject < ActiveRecord::Base
protected
def set_email_address
- if self.new_record?
+ unless self.persisted?
self.author_email_address = 'test@test.com'
end
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index 82d4b5997f..6496f36f7e 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -89,7 +89,7 @@ class Topic < ActiveRecord::Base
end
def set_email_address
- if self.new_record?
+ unless self.persisted?
self.author_email_address = 'test@test.com'
end
end