activerecord 3.2.22.5 → 5.2.8
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of activerecord might be problematic. Click here for more details.
- checksums.yaml +5 -5
- data/CHANGELOG.md +657 -621
- data/MIT-LICENSE +2 -2
- data/README.rdoc +41 -46
- data/examples/performance.rb +55 -42
- data/examples/simple.rb +6 -5
- data/lib/active_record/aggregations.rb +264 -236
- data/lib/active_record/association_relation.rb +40 -0
- data/lib/active_record/associations/alias_tracker.rb +47 -42
- data/lib/active_record/associations/association.rb +127 -75
- data/lib/active_record/associations/association_scope.rb +126 -92
- data/lib/active_record/associations/belongs_to_association.rb +78 -27
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +9 -4
- data/lib/active_record/associations/builder/association.rb +117 -32
- data/lib/active_record/associations/builder/belongs_to.rb +135 -60
- data/lib/active_record/associations/builder/collection_association.rb +61 -54
- data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +120 -42
- data/lib/active_record/associations/builder/has_many.rb +10 -64
- data/lib/active_record/associations/builder/has_one.rb +19 -51
- data/lib/active_record/associations/builder/singular_association.rb +28 -18
- data/lib/active_record/associations/collection_association.rb +226 -293
- data/lib/active_record/associations/collection_proxy.rb +1067 -69
- data/lib/active_record/associations/foreign_association.rb +13 -0
- data/lib/active_record/associations/has_many_association.rb +83 -47
- data/lib/active_record/associations/has_many_through_association.rb +98 -65
- data/lib/active_record/associations/has_one_association.rb +57 -20
- data/lib/active_record/associations/has_one_through_association.rb +18 -9
- data/lib/active_record/associations/join_dependency/join_association.rb +48 -126
- data/lib/active_record/associations/join_dependency/join_base.rb +11 -12
- data/lib/active_record/associations/join_dependency/join_part.rb +35 -42
- data/lib/active_record/associations/join_dependency.rb +212 -164
- data/lib/active_record/associations/preloader/association.rb +95 -89
- data/lib/active_record/associations/preloader/through_association.rb +84 -44
- data/lib/active_record/associations/preloader.rb +123 -111
- data/lib/active_record/associations/singular_association.rb +33 -24
- data/lib/active_record/associations/through_association.rb +60 -26
- data/lib/active_record/associations.rb +1759 -1506
- data/lib/active_record/attribute_assignment.rb +60 -193
- data/lib/active_record/attribute_decorators.rb +90 -0
- data/lib/active_record/attribute_methods/before_type_cast.rb +55 -8
- data/lib/active_record/attribute_methods/dirty.rb +113 -74
- data/lib/active_record/attribute_methods/primary_key.rb +106 -77
- data/lib/active_record/attribute_methods/query.rb +8 -5
- data/lib/active_record/attribute_methods/read.rb +63 -114
- data/lib/active_record/attribute_methods/serialization.rb +60 -90
- data/lib/active_record/attribute_methods/time_zone_conversion.rb +69 -43
- data/lib/active_record/attribute_methods/write.rb +43 -45
- data/lib/active_record/attribute_methods.rb +366 -149
- data/lib/active_record/attributes.rb +266 -0
- data/lib/active_record/autosave_association.rb +312 -225
- data/lib/active_record/base.rb +114 -505
- data/lib/active_record/callbacks.rb +145 -67
- data/lib/active_record/coders/json.rb +15 -0
- data/lib/active_record/coders/yaml_column.rb +32 -23
- data/lib/active_record/collection_cache_key.rb +53 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +883 -284
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +16 -2
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +350 -200
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -27
- data/lib/active_record/connection_adapters/abstract/quoting.rb +150 -65
- data/lib/active_record/connection_adapters/abstract/savepoints.rb +23 -0
- data/lib/active_record/connection_adapters/abstract/schema_creation.rb +146 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +477 -284
- data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +95 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +1100 -310
- data/lib/active_record/connection_adapters/abstract/transaction.rb +283 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +450 -118
- data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +657 -446
- data/lib/active_record/connection_adapters/column.rb +50 -255
- data/lib/active_record/connection_adapters/connection_specification.rb +287 -0
- data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +33 -0
- data/lib/active_record/connection_adapters/mysql/column.rb +27 -0
- data/lib/active_record/connection_adapters/mysql/database_statements.rb +140 -0
- data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +72 -0
- data/lib/active_record/connection_adapters/mysql/quoting.rb +44 -0
- data/lib/active_record/connection_adapters/mysql/schema_creation.rb +73 -0
- data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +87 -0
- data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +80 -0
- data/lib/active_record/connection_adapters/mysql/schema_statements.rb +148 -0
- data/lib/active_record/connection_adapters/mysql/type_metadata.rb +35 -0
- data/lib/active_record/connection_adapters/mysql2_adapter.rb +59 -210
- data/lib/active_record/connection_adapters/postgresql/column.rb +44 -0
- data/lib/active_record/connection_adapters/postgresql/database_statements.rb +163 -0
- data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +44 -0
- data/lib/active_record/connection_adapters/postgresql/oid/array.rb +92 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +56 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +17 -0
- data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +50 -0
- data/lib/active_record/connection_adapters/postgresql/oid/date.rb +23 -0
- data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +23 -0
- data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +21 -0
- data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +71 -0
- data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +45 -0
- data/lib/active_record/connection_adapters/postgresql/oid/money.rb +41 -0
- data/lib/active_record/connection_adapters/postgresql/oid/oid.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/point.rb +65 -0
- data/lib/active_record/connection_adapters/postgresql/oid/range.rb +97 -0
- data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +18 -0
- data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +111 -0
- data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +23 -0
- data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +28 -0
- data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +30 -0
- data/lib/active_record/connection_adapters/postgresql/oid.rb +34 -0
- data/lib/active_record/connection_adapters/postgresql/quoting.rb +168 -0
- data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +43 -0
- data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +65 -0
- data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +206 -0
- data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +50 -0
- data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +774 -0
- data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +39 -0
- data/lib/active_record/connection_adapters/postgresql/utils.rb +81 -0
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +620 -1080
- data/lib/active_record/connection_adapters/schema_cache.rb +85 -36
- data/lib/active_record/connection_adapters/sql_type_metadata.rb +34 -0
- data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +21 -0
- data/lib/active_record/connection_adapters/sqlite3/quoting.rb +67 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +17 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +19 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb +18 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +106 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +545 -27
- data/lib/active_record/connection_adapters/statement_pool.rb +34 -13
- data/lib/active_record/connection_handling.rb +145 -0
- data/lib/active_record/core.rb +559 -0
- data/lib/active_record/counter_cache.rb +200 -105
- data/lib/active_record/define_callbacks.rb +22 -0
- data/lib/active_record/dynamic_matchers.rb +107 -69
- data/lib/active_record/enum.rb +244 -0
- data/lib/active_record/errors.rb +245 -60
- data/lib/active_record/explain.rb +35 -71
- data/lib/active_record/explain_registry.rb +32 -0
- data/lib/active_record/explain_subscriber.rb +18 -9
- data/lib/active_record/fixture_set/file.rb +82 -0
- data/lib/active_record/fixtures.rb +418 -275
- data/lib/active_record/gem_version.rb +17 -0
- data/lib/active_record/inheritance.rb +209 -100
- data/lib/active_record/integration.rb +116 -21
- data/lib/active_record/internal_metadata.rb +45 -0
- data/lib/active_record/legacy_yaml_adapter.rb +48 -0
- data/lib/active_record/locale/en.yml +9 -1
- data/lib/active_record/locking/optimistic.rb +107 -94
- data/lib/active_record/locking/pessimistic.rb +20 -8
- data/lib/active_record/log_subscriber.rb +99 -34
- data/lib/active_record/migration/command_recorder.rb +199 -64
- data/lib/active_record/migration/compatibility.rb +217 -0
- data/lib/active_record/migration/join_table.rb +17 -0
- data/lib/active_record/migration.rb +893 -296
- data/lib/active_record/model_schema.rb +328 -175
- data/lib/active_record/nested_attributes.rb +338 -242
- data/lib/active_record/no_touching.rb +58 -0
- data/lib/active_record/null_relation.rb +68 -0
- data/lib/active_record/persistence.rb +557 -170
- data/lib/active_record/query_cache.rb +14 -43
- data/lib/active_record/querying.rb +36 -24
- data/lib/active_record/railtie.rb +147 -52
- data/lib/active_record/railties/console_sandbox.rb +5 -4
- data/lib/active_record/railties/controller_runtime.rb +13 -6
- data/lib/active_record/railties/databases.rake +206 -488
- data/lib/active_record/readonly_attributes.rb +4 -6
- data/lib/active_record/reflection.rb +734 -228
- data/lib/active_record/relation/batches/batch_enumerator.rb +69 -0
- data/lib/active_record/relation/batches.rb +249 -52
- data/lib/active_record/relation/calculations.rb +330 -284
- data/lib/active_record/relation/delegation.rb +135 -37
- data/lib/active_record/relation/finder_methods.rb +450 -287
- data/lib/active_record/relation/from_clause.rb +26 -0
- data/lib/active_record/relation/merger.rb +193 -0
- data/lib/active_record/relation/predicate_builder/array_handler.rb +48 -0
- data/lib/active_record/relation/predicate_builder/association_query_value.rb +46 -0
- data/lib/active_record/relation/predicate_builder/base_handler.rb +19 -0
- data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +20 -0
- data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +56 -0
- data/lib/active_record/relation/predicate_builder/range_handler.rb +42 -0
- data/lib/active_record/relation/predicate_builder/relation_handler.rb +19 -0
- data/lib/active_record/relation/predicate_builder.rb +132 -43
- data/lib/active_record/relation/query_attribute.rb +45 -0
- data/lib/active_record/relation/query_methods.rb +1037 -221
- data/lib/active_record/relation/record_fetch_warning.rb +51 -0
- data/lib/active_record/relation/spawn_methods.rb +48 -151
- data/lib/active_record/relation/where_clause.rb +186 -0
- data/lib/active_record/relation/where_clause_factory.rb +34 -0
- data/lib/active_record/relation.rb +451 -359
- data/lib/active_record/result.rb +129 -20
- data/lib/active_record/runtime_registry.rb +24 -0
- data/lib/active_record/sanitization.rb +164 -136
- data/lib/active_record/schema.rb +31 -19
- data/lib/active_record/schema_dumper.rb +154 -107
- data/lib/active_record/schema_migration.rb +56 -0
- data/lib/active_record/scoping/default.rb +108 -98
- data/lib/active_record/scoping/named.rb +125 -112
- data/lib/active_record/scoping.rb +77 -123
- data/lib/active_record/secure_token.rb +40 -0
- data/lib/active_record/serialization.rb +10 -6
- data/lib/active_record/statement_cache.rb +121 -0
- data/lib/active_record/store.rb +175 -16
- data/lib/active_record/suppressor.rb +61 -0
- data/lib/active_record/table_metadata.rb +82 -0
- data/lib/active_record/tasks/database_tasks.rb +337 -0
- data/lib/active_record/tasks/mysql_database_tasks.rb +115 -0
- data/lib/active_record/tasks/postgresql_database_tasks.rb +143 -0
- data/lib/active_record/tasks/sqlite_database_tasks.rb +83 -0
- data/lib/active_record/timestamp.rb +80 -41
- data/lib/active_record/touch_later.rb +64 -0
- data/lib/active_record/transactions.rb +240 -119
- data/lib/active_record/translation.rb +2 -0
- data/lib/active_record/type/adapter_specific_registry.rb +136 -0
- data/lib/active_record/type/date.rb +9 -0
- data/lib/active_record/type/date_time.rb +9 -0
- data/lib/active_record/type/decimal_without_scale.rb +15 -0
- data/lib/active_record/type/hash_lookup_type_map.rb +25 -0
- data/lib/active_record/type/internal/timezone.rb +17 -0
- data/lib/active_record/type/json.rb +30 -0
- data/lib/active_record/type/serialized.rb +71 -0
- data/lib/active_record/type/text.rb +11 -0
- data/lib/active_record/type/time.rb +21 -0
- data/lib/active_record/type/type_map.rb +62 -0
- data/lib/active_record/type/unsigned_integer.rb +17 -0
- data/lib/active_record/type.rb +79 -0
- data/lib/active_record/type_caster/connection.rb +33 -0
- data/lib/active_record/type_caster/map.rb +23 -0
- data/lib/active_record/type_caster.rb +9 -0
- data/lib/active_record/validations/absence.rb +25 -0
- data/lib/active_record/validations/associated.rb +35 -18
- data/lib/active_record/validations/length.rb +26 -0
- data/lib/active_record/validations/presence.rb +68 -0
- data/lib/active_record/validations/uniqueness.rb +133 -75
- data/lib/active_record/validations.rb +53 -43
- data/lib/active_record/version.rb +7 -7
- data/lib/active_record.rb +89 -57
- data/lib/rails/generators/active_record/application_record/application_record_generator.rb +27 -0
- data/lib/rails/generators/active_record/application_record/templates/application_record.rb.tt +5 -0
- data/lib/rails/generators/active_record/migration/migration_generator.rb +61 -8
- data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +24 -0
- data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +46 -0
- data/lib/rails/generators/active_record/migration.rb +28 -8
- data/lib/rails/generators/active_record/model/model_generator.rb +23 -22
- data/lib/rails/generators/active_record/model/templates/model.rb.tt +13 -0
- data/lib/rails/generators/active_record/model/templates/{module.rb → module.rb.tt} +1 -1
- data/lib/rails/generators/active_record.rb +10 -16
- metadata +141 -62
- data/examples/associations.png +0 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +0 -63
- data/lib/active_record/associations/join_helper.rb +0 -55
- data/lib/active_record/associations/preloader/belongs_to.rb +0 -17
- data/lib/active_record/associations/preloader/collection_association.rb +0 -24
- data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +0 -60
- data/lib/active_record/associations/preloader/has_many.rb +0 -17
- data/lib/active_record/associations/preloader/has_many_through.rb +0 -15
- data/lib/active_record/associations/preloader/has_one.rb +0 -23
- data/lib/active_record/associations/preloader/has_one_through.rb +0 -9
- data/lib/active_record/associations/preloader/singular_association.rb +0 -21
- data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +0 -32
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +0 -191
- data/lib/active_record/connection_adapters/mysql_adapter.rb +0 -441
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -583
- data/lib/active_record/dynamic_finder_match.rb +0 -68
- data/lib/active_record/dynamic_scope_match.rb +0 -23
- data/lib/active_record/fixtures/file.rb +0 -65
- data/lib/active_record/identity_map.rb +0 -162
- data/lib/active_record/observer.rb +0 -121
- data/lib/active_record/railties/jdbcmysql_error.rb +0 -16
- data/lib/active_record/serializers/xml_serializer.rb +0 -203
- data/lib/active_record/session_store.rb +0 -360
- data/lib/active_record/test_case.rb +0 -73
- data/lib/rails/generators/active_record/migration/templates/migration.rb +0 -34
- data/lib/rails/generators/active_record/model/templates/migration.rb +0 -15
- data/lib/rails/generators/active_record/model/templates/model.rb +0 -12
- data/lib/rails/generators/active_record/observer/observer_generator.rb +0 -15
- data/lib/rails/generators/active_record/observer/templates/observer.rb +0 -4
- data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +0 -25
- data/lib/rails/generators/active_record/session_migration/templates/migration.rb +0 -12
@@ -1,7 +1,7 @@
|
|
1
|
-
|
1
|
+
# frozen_string_literal: true
|
2
2
|
|
3
3
|
module ActiveRecord
|
4
|
-
# = Active Record Persistence
|
4
|
+
# = Active Record \Persistence
|
5
5
|
module Persistence
|
6
6
|
extend ActiveSupport::Concern
|
7
7
|
|
@@ -9,99 +9,303 @@ module ActiveRecord
|
|
9
9
|
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
|
10
10
|
# The resulting object is returned whether the object was saved successfully to the database or not.
|
11
11
|
#
|
12
|
-
# The +attributes+ parameter can be either
|
12
|
+
# The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
|
13
13
|
# attributes on the objects that are to be created.
|
14
14
|
#
|
15
|
-
# +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
|
16
|
-
# in the +options+ parameter.
|
17
|
-
#
|
18
15
|
# ==== Examples
|
19
16
|
# # Create a single new object
|
20
|
-
# User.create(:
|
21
|
-
#
|
22
|
-
# # Create a single new object using the :admin mass-assignment security role
|
23
|
-
# User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
|
24
|
-
#
|
25
|
-
# # Create a single new object bypassing mass-assignment security
|
26
|
-
# User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
|
17
|
+
# User.create(first_name: 'Jamie')
|
27
18
|
#
|
28
19
|
# # Create an Array of new objects
|
29
|
-
# User.create([{ :
|
20
|
+
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
|
30
21
|
#
|
31
22
|
# # Create a single object and pass it into a block to set other attributes.
|
32
|
-
# User.create(:
|
23
|
+
# User.create(first_name: 'Jamie') do |u|
|
33
24
|
# u.is_admin = false
|
34
25
|
# end
|
35
26
|
#
|
36
27
|
# # Creating an Array of new objects using a block, where the block is executed for each object:
|
37
|
-
# User.create([{ :
|
28
|
+
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
|
38
29
|
# u.is_admin = false
|
39
30
|
# end
|
40
|
-
def create(attributes = nil,
|
31
|
+
def create(attributes = nil, &block)
|
41
32
|
if attributes.is_a?(Array)
|
42
|
-
attributes.collect { |attr| create(attr,
|
33
|
+
attributes.collect { |attr| create(attr, &block) }
|
43
34
|
else
|
44
|
-
object = new(attributes,
|
35
|
+
object = new(attributes, &block)
|
45
36
|
object.save
|
46
37
|
object
|
47
38
|
end
|
48
39
|
end
|
40
|
+
|
41
|
+
# Creates an object (or multiple objects) and saves it to the database,
|
42
|
+
# if validations pass. Raises a RecordInvalid error if validations fail,
|
43
|
+
# unlike Base#create.
|
44
|
+
#
|
45
|
+
# The +attributes+ parameter can be either a Hash or an Array of Hashes.
|
46
|
+
# These describe which attributes to be created on the object, or
|
47
|
+
# multiple objects when given an Array of Hashes.
|
48
|
+
def create!(attributes = nil, &block)
|
49
|
+
if attributes.is_a?(Array)
|
50
|
+
attributes.collect { |attr| create!(attr, &block) }
|
51
|
+
else
|
52
|
+
object = new(attributes, &block)
|
53
|
+
object.save!
|
54
|
+
object
|
55
|
+
end
|
56
|
+
end
|
57
|
+
|
58
|
+
# Given an attributes hash, +instantiate+ returns a new instance of
|
59
|
+
# the appropriate class. Accepts only keys as strings.
|
60
|
+
#
|
61
|
+
# For example, +Post.all+ may return Comments, Messages, and Emails
|
62
|
+
# by storing the record's subclass in a +type+ attribute. By calling
|
63
|
+
# +instantiate+ instead of +new+, finder methods ensure they get new
|
64
|
+
# instances of the appropriate class for each record.
|
65
|
+
#
|
66
|
+
# See <tt>ActiveRecord::Inheritance#discriminate_class_for_record</tt> to see
|
67
|
+
# how this "single-table" inheritance mapping is implemented.
|
68
|
+
def instantiate(attributes, column_types = {}, &block)
|
69
|
+
klass = discriminate_class_for_record(attributes)
|
70
|
+
attributes = klass.attributes_builder.build_from_database(attributes, column_types)
|
71
|
+
klass.allocate.init_with("attributes" => attributes, "new_record" => false, &block)
|
72
|
+
end
|
73
|
+
|
74
|
+
# Updates an object (or multiple objects) and saves it to the database, if validations pass.
|
75
|
+
# The resulting object is returned whether the object was saved successfully to the database or not.
|
76
|
+
#
|
77
|
+
# ==== Parameters
|
78
|
+
#
|
79
|
+
# * +id+ - This should be the id or an array of ids to be updated.
|
80
|
+
# * +attributes+ - This should be a hash of attributes or an array of hashes.
|
81
|
+
#
|
82
|
+
# ==== Examples
|
83
|
+
#
|
84
|
+
# # Updates one record
|
85
|
+
# Person.update(15, user_name: "Samuel", group: "expert")
|
86
|
+
#
|
87
|
+
# # Updates multiple records
|
88
|
+
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
|
89
|
+
# Person.update(people.keys, people.values)
|
90
|
+
#
|
91
|
+
# # Updates multiple records from the result of a relation
|
92
|
+
# people = Person.where(group: "expert")
|
93
|
+
# people.update(group: "masters")
|
94
|
+
#
|
95
|
+
# Note: Updating a large number of records will run an UPDATE
|
96
|
+
# query for each record, which may cause a performance issue.
|
97
|
+
# When running callbacks is not needed for each record update,
|
98
|
+
# it is preferred to use {update_all}[rdoc-ref:Relation#update_all]
|
99
|
+
# for updating all records in a single query.
|
100
|
+
def update(id = :all, attributes)
|
101
|
+
if id.is_a?(Array)
|
102
|
+
id.map { |one_id| find(one_id) }.each_with_index { |object, idx|
|
103
|
+
object.update(attributes[idx])
|
104
|
+
}
|
105
|
+
elsif id == :all
|
106
|
+
all.each { |record| record.update(attributes) }
|
107
|
+
else
|
108
|
+
if ActiveRecord::Base === id
|
109
|
+
raise ArgumentError,
|
110
|
+
"You are passing an instance of ActiveRecord::Base to `update`. " \
|
111
|
+
"Please pass the id of the object by calling `.id`."
|
112
|
+
end
|
113
|
+
object = find(id)
|
114
|
+
object.update(attributes)
|
115
|
+
object
|
116
|
+
end
|
117
|
+
end
|
118
|
+
|
119
|
+
# Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
|
120
|
+
# therefore all callbacks and filters are fired off before the object is deleted. This method is
|
121
|
+
# less efficient than #delete but allows cleanup methods and other actions to be run.
|
122
|
+
#
|
123
|
+
# This essentially finds the object (or multiple objects) with the given id, creates a new object
|
124
|
+
# from the attributes, and then calls destroy on it.
|
125
|
+
#
|
126
|
+
# ==== Parameters
|
127
|
+
#
|
128
|
+
# * +id+ - This should be the id or an array of ids to be destroyed.
|
129
|
+
#
|
130
|
+
# ==== Examples
|
131
|
+
#
|
132
|
+
# # Destroy a single object
|
133
|
+
# Todo.destroy(1)
|
134
|
+
#
|
135
|
+
# # Destroy multiple objects
|
136
|
+
# todos = [1,2,3]
|
137
|
+
# Todo.destroy(todos)
|
138
|
+
def destroy(id)
|
139
|
+
if id.is_a?(Array)
|
140
|
+
find(id).each(&:destroy)
|
141
|
+
else
|
142
|
+
find(id).destroy
|
143
|
+
end
|
144
|
+
end
|
145
|
+
|
146
|
+
# Deletes the row with a primary key matching the +id+ argument, using a
|
147
|
+
# SQL +DELETE+ statement, and returns the number of rows deleted. Active
|
148
|
+
# Record objects are not instantiated, so the object's callbacks are not
|
149
|
+
# executed, including any <tt>:dependent</tt> association options.
|
150
|
+
#
|
151
|
+
# You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
|
152
|
+
#
|
153
|
+
# Note: Although it is often much faster than the alternative, #destroy,
|
154
|
+
# skipping callbacks might bypass business logic in your application
|
155
|
+
# that ensures referential integrity or performs other essential jobs.
|
156
|
+
#
|
157
|
+
# ==== Examples
|
158
|
+
#
|
159
|
+
# # Delete a single row
|
160
|
+
# Todo.delete(1)
|
161
|
+
#
|
162
|
+
# # Delete multiple rows
|
163
|
+
# Todo.delete([2,3,4])
|
164
|
+
def delete(id_or_array)
|
165
|
+
where(primary_key => id_or_array).delete_all
|
166
|
+
end
|
167
|
+
|
168
|
+
def _insert_record(values) # :nodoc:
|
169
|
+
primary_key_value = nil
|
170
|
+
|
171
|
+
if primary_key && Hash === values
|
172
|
+
primary_key_value = values[primary_key]
|
173
|
+
|
174
|
+
if !primary_key_value && prefetch_primary_key?
|
175
|
+
primary_key_value = next_sequence_value
|
176
|
+
values[primary_key] = primary_key_value
|
177
|
+
end
|
178
|
+
end
|
179
|
+
|
180
|
+
if values.empty?
|
181
|
+
im = arel_table.compile_insert(connection.empty_insert_statement_value)
|
182
|
+
im.into arel_table
|
183
|
+
else
|
184
|
+
im = arel_table.compile_insert(_substitute_values(values))
|
185
|
+
end
|
186
|
+
|
187
|
+
connection.insert(im, "#{self} Create", primary_key || false, primary_key_value)
|
188
|
+
end
|
189
|
+
|
190
|
+
def _update_record(values, constraints) # :nodoc:
|
191
|
+
constraints = _substitute_values(constraints).map { |attr, bind| attr.eq(bind) }
|
192
|
+
|
193
|
+
um = arel_table.where(
|
194
|
+
constraints.reduce(&:and)
|
195
|
+
).compile_update(_substitute_values(values), primary_key)
|
196
|
+
|
197
|
+
connection.update(um, "#{self} Update")
|
198
|
+
end
|
199
|
+
|
200
|
+
def _delete_record(constraints) # :nodoc:
|
201
|
+
constraints = _substitute_values(constraints).map { |attr, bind| attr.eq(bind) }
|
202
|
+
|
203
|
+
dm = Arel::DeleteManager.new
|
204
|
+
dm.from(arel_table)
|
205
|
+
dm.wheres = constraints
|
206
|
+
|
207
|
+
connection.delete(dm, "#{self} Destroy")
|
208
|
+
end
|
209
|
+
|
210
|
+
private
|
211
|
+
# Called by +instantiate+ to decide which class to use for a new
|
212
|
+
# record instance.
|
213
|
+
#
|
214
|
+
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ for
|
215
|
+
# the single-table inheritance discriminator.
|
216
|
+
def discriminate_class_for_record(record)
|
217
|
+
self
|
218
|
+
end
|
219
|
+
|
220
|
+
def _substitute_values(values)
|
221
|
+
values.map do |name, value|
|
222
|
+
attr = arel_attribute(name)
|
223
|
+
bind = predicate_builder.build_bind_attribute(name, value)
|
224
|
+
[attr, bind]
|
225
|
+
end
|
226
|
+
end
|
49
227
|
end
|
50
228
|
|
51
229
|
# Returns true if this object hasn't been saved yet -- that is, a record
|
52
|
-
# for the object doesn't exist in the
|
230
|
+
# for the object doesn't exist in the database yet; otherwise, returns false.
|
53
231
|
def new_record?
|
232
|
+
sync_with_transaction_state
|
54
233
|
@new_record
|
55
234
|
end
|
56
235
|
|
57
236
|
# Returns true if this object has been destroyed, otherwise returns false.
|
58
237
|
def destroyed?
|
238
|
+
sync_with_transaction_state
|
59
239
|
@destroyed
|
60
240
|
end
|
61
241
|
|
62
|
-
# Returns if the record is persisted, i.e. it's not a new record and it was
|
63
|
-
# not destroyed.
|
242
|
+
# Returns true if the record is persisted, i.e. it's not a new record and it was
|
243
|
+
# not destroyed, otherwise returns false.
|
64
244
|
def persisted?
|
65
|
-
|
245
|
+
sync_with_transaction_state
|
246
|
+
!(@new_record || @destroyed)
|
66
247
|
end
|
67
248
|
|
249
|
+
##
|
250
|
+
# :call-seq:
|
251
|
+
# save(*args)
|
252
|
+
#
|
68
253
|
# Saves the model.
|
69
254
|
#
|
70
|
-
# If the model is new a record gets created in the database, otherwise
|
255
|
+
# If the model is new, a record gets created in the database, otherwise
|
71
256
|
# the existing record gets updated.
|
72
257
|
#
|
73
|
-
# By default, save always
|
74
|
-
# is cancelled and
|
75
|
-
# :
|
258
|
+
# By default, save always runs validations. If any of them fail the action
|
259
|
+
# is cancelled and #save returns +false+, and the record won't be saved. However, if you supply
|
260
|
+
# <tt>validate: false</tt>, validations are bypassed altogether. See
|
76
261
|
# ActiveRecord::Validations for more information.
|
77
262
|
#
|
78
|
-
#
|
79
|
-
#
|
80
|
-
#
|
263
|
+
# By default, #save also sets the +updated_at+/+updated_on+ attributes to
|
264
|
+
# the current time. However, if you supply <tt>touch: false</tt>, these
|
265
|
+
# timestamps will not be updated.
|
266
|
+
#
|
267
|
+
# There's a series of callbacks associated with #save. If any of the
|
268
|
+
# <tt>before_*</tt> callbacks throws +:abort+ the action is cancelled and
|
269
|
+
# #save returns +false+. See ActiveRecord::Callbacks for further
|
81
270
|
# details.
|
82
|
-
|
83
|
-
|
84
|
-
|
85
|
-
|
86
|
-
|
87
|
-
|
271
|
+
#
|
272
|
+
# Attributes marked as readonly are silently ignored if the record is
|
273
|
+
# being updated.
|
274
|
+
def save(*args, &block)
|
275
|
+
create_or_update(*args, &block)
|
276
|
+
rescue ActiveRecord::RecordInvalid
|
277
|
+
false
|
88
278
|
end
|
89
279
|
|
280
|
+
##
|
281
|
+
# :call-seq:
|
282
|
+
# save!(*args)
|
283
|
+
#
|
90
284
|
# Saves the model.
|
91
285
|
#
|
92
|
-
# If the model is new a record gets created in the database, otherwise
|
286
|
+
# If the model is new, a record gets created in the database, otherwise
|
93
287
|
# the existing record gets updated.
|
94
288
|
#
|
95
|
-
#
|
96
|
-
# ActiveRecord::RecordInvalid gets raised.
|
97
|
-
#
|
289
|
+
# By default, #save! always runs validations. If any of them fail
|
290
|
+
# ActiveRecord::RecordInvalid gets raised, and the record won't be saved. However, if you supply
|
291
|
+
# <tt>validate: false</tt>, validations are bypassed altogether. See
|
292
|
+
# ActiveRecord::Validations for more information.
|
293
|
+
#
|
294
|
+
# By default, #save! also sets the +updated_at+/+updated_on+ attributes to
|
295
|
+
# the current time. However, if you supply <tt>touch: false</tt>, these
|
296
|
+
# timestamps will not be updated.
|
98
297
|
#
|
99
|
-
# There's a series of callbacks associated with
|
100
|
-
# the <tt>before_*</tt> callbacks
|
101
|
-
# and
|
298
|
+
# There's a series of callbacks associated with #save!. If any of
|
299
|
+
# the <tt>before_*</tt> callbacks throws +:abort+ the action is cancelled
|
300
|
+
# and #save! raises ActiveRecord::RecordNotSaved. See
|
102
301
|
# ActiveRecord::Callbacks for further details.
|
103
|
-
|
104
|
-
|
302
|
+
#
|
303
|
+
# Attributes marked as readonly are silently ignored if the record is
|
304
|
+
# being updated.
|
305
|
+
#
|
306
|
+
# Unless an error is raised, returns true.
|
307
|
+
def save!(*args, &block)
|
308
|
+
create_or_update(*args, &block) || raise(RecordNotSaved.new("Failed to save the record", self))
|
105
309
|
end
|
106
310
|
|
107
311
|
# Deletes the record in the database and freezes this instance to
|
@@ -111,58 +315,85 @@ module ActiveRecord
|
|
111
315
|
# The row is simply removed with an SQL +DELETE+ statement on the
|
112
316
|
# record's primary key, and no callbacks are executed.
|
113
317
|
#
|
318
|
+
# Note that this will also delete records marked as {#readonly?}[rdoc-ref:Core#readonly?].
|
319
|
+
#
|
114
320
|
# To enforce the object's +before_destroy+ and +after_destroy+
|
115
|
-
# callbacks
|
321
|
+
# callbacks or any <tt>:dependent</tt> association
|
116
322
|
# options, use <tt>#destroy</tt>.
|
117
323
|
def delete
|
118
|
-
if persisted?
|
119
|
-
self.class.delete(id)
|
120
|
-
IdentityMap.remove(self) if IdentityMap.enabled?
|
121
|
-
end
|
324
|
+
_delete_row if persisted?
|
122
325
|
@destroyed = true
|
123
326
|
freeze
|
124
327
|
end
|
125
328
|
|
126
329
|
# Deletes the record in the database and freezes this instance to reflect
|
127
330
|
# that no changes should be made (since they can't be persisted).
|
331
|
+
#
|
332
|
+
# There's a series of callbacks associated with #destroy. If the
|
333
|
+
# <tt>before_destroy</tt> callback throws +:abort+ the action is cancelled
|
334
|
+
# and #destroy returns +false+.
|
335
|
+
# See ActiveRecord::Callbacks for further details.
|
128
336
|
def destroy
|
337
|
+
_raise_readonly_record_error if readonly?
|
129
338
|
destroy_associations
|
130
|
-
|
131
|
-
if persisted?
|
132
|
-
|
133
|
-
|
134
|
-
|
135
|
-
substitute = connection.substitute_at(column, 0)
|
136
|
-
|
137
|
-
relation = self.class.unscoped.where(
|
138
|
-
self.class.arel_table[pk].eq(substitute))
|
139
|
-
|
140
|
-
relation.bind_values = [[column, id]]
|
141
|
-
relation.delete_all
|
339
|
+
self.class.connection.add_transaction_record(self)
|
340
|
+
@_trigger_destroy_callback = if persisted?
|
341
|
+
destroy_row > 0
|
342
|
+
else
|
343
|
+
true
|
142
344
|
end
|
143
|
-
|
144
345
|
@destroyed = true
|
145
346
|
freeze
|
146
347
|
end
|
147
348
|
|
349
|
+
# Deletes the record in the database and freezes this instance to reflect
|
350
|
+
# that no changes should be made (since they can't be persisted).
|
351
|
+
#
|
352
|
+
# There's a series of callbacks associated with #destroy!. If the
|
353
|
+
# <tt>before_destroy</tt> callback throws +:abort+ the action is cancelled
|
354
|
+
# and #destroy! raises ActiveRecord::RecordNotDestroyed.
|
355
|
+
# See ActiveRecord::Callbacks for further details.
|
356
|
+
def destroy!
|
357
|
+
destroy || _raise_record_not_destroyed
|
358
|
+
end
|
359
|
+
|
148
360
|
# Returns an instance of the specified +klass+ with the attributes of the
|
149
361
|
# current record. This is mostly useful in relation to single-table
|
150
362
|
# inheritance structures where you want a subclass to appear as the
|
151
363
|
# superclass. This can be used along with record identification in
|
152
364
|
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
|
153
|
-
# like render <tt
|
365
|
+
# like render <tt>partial: @client.becomes(Company)</tt> to render that
|
154
366
|
# instance using the companies/company partial instead of clients/client.
|
155
367
|
#
|
156
368
|
# Note: The new instance will share a link to the same attributes as the original class.
|
157
|
-
#
|
369
|
+
# Therefore the sti column value will still be the same.
|
370
|
+
# Any change to the attributes on either instance will affect both instances.
|
371
|
+
# If you want to change the sti column as well, use #becomes! instead.
|
158
372
|
def becomes(klass)
|
159
|
-
became = klass.
|
373
|
+
became = klass.allocate
|
374
|
+
became.send(:initialize)
|
160
375
|
became.instance_variable_set("@attributes", @attributes)
|
161
|
-
became.instance_variable_set("@
|
376
|
+
became.instance_variable_set("@mutations_from_database", @mutations_from_database ||= nil)
|
377
|
+
became.instance_variable_set("@changed_attributes", attributes_changed_by_setter)
|
162
378
|
became.instance_variable_set("@new_record", new_record?)
|
163
379
|
became.instance_variable_set("@destroyed", destroyed?)
|
164
|
-
became.
|
165
|
-
became
|
380
|
+
became.errors.copy!(errors)
|
381
|
+
became
|
382
|
+
end
|
383
|
+
|
384
|
+
# Wrapper around #becomes that also changes the instance's sti column value.
|
385
|
+
# This is especially useful if you want to persist the changed class in your
|
386
|
+
# database.
|
387
|
+
#
|
388
|
+
# Note: The old instance's sti column value will be changed too, as both objects
|
389
|
+
# share the same set of attributes.
|
390
|
+
def becomes!(klass)
|
391
|
+
became = becomes(klass)
|
392
|
+
sti_type = nil
|
393
|
+
if !klass.descends_from_active_record?
|
394
|
+
sti_type = klass.sti_name
|
395
|
+
end
|
396
|
+
became.public_send("#{klass.inheritance_column}=", sti_type)
|
166
397
|
became
|
167
398
|
end
|
168
399
|
|
@@ -170,65 +401,91 @@ module ActiveRecord
|
|
170
401
|
# This is especially useful for boolean flags on existing records. Also note that
|
171
402
|
#
|
172
403
|
# * Validation is skipped.
|
173
|
-
# * Callbacks are invoked.
|
404
|
+
# * \Callbacks are invoked.
|
174
405
|
# * updated_at/updated_on column is updated if that column is available.
|
175
406
|
# * Updates all the attributes that are dirty in this object.
|
176
407
|
#
|
177
|
-
|
178
|
-
name = name.to_s
|
179
|
-
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
|
180
|
-
send("#{name}=", value)
|
181
|
-
save(:validate => false)
|
182
|
-
end
|
183
|
-
|
184
|
-
# Updates a single attribute of an object, without calling save.
|
185
|
-
#
|
186
|
-
# * Validation is skipped.
|
187
|
-
# * Callbacks are skipped.
|
188
|
-
# * updated_at/updated_on column is not updated if that column is available.
|
189
|
-
#
|
190
|
-
# Raises an +ActiveRecordError+ when called on new objects, or when the +name+
|
408
|
+
# This method raises an ActiveRecord::ActiveRecordError if the
|
191
409
|
# attribute is marked as readonly.
|
192
|
-
|
410
|
+
#
|
411
|
+
# Also see #update_column.
|
412
|
+
def update_attribute(name, value)
|
193
413
|
name = name.to_s
|
194
|
-
|
195
|
-
|
414
|
+
verify_readonly_attribute(name)
|
415
|
+
public_send("#{name}=", value)
|
196
416
|
|
197
|
-
|
198
|
-
|
199
|
-
raw_write_attribute(name, value)
|
200
|
-
|
201
|
-
updated_count == 1
|
417
|
+
save(validate: false)
|
202
418
|
end
|
203
419
|
|
204
420
|
# Updates the attributes of the model from the passed-in hash and saves the
|
205
421
|
# record, all wrapped in a transaction. If the object is invalid, the saving
|
206
422
|
# will fail and false will be returned.
|
207
|
-
|
208
|
-
# When updating model attributes, mass-assignment security protection is respected.
|
209
|
-
# If no +:as+ option is supplied then the +:default+ role will be used.
|
210
|
-
# If you want to bypass the protection given by +attr_protected+ and
|
211
|
-
# +attr_accessible+ then you can do so using the +:without_protection+ option.
|
212
|
-
def update_attributes(attributes, options = {})
|
423
|
+
def update(attributes)
|
213
424
|
# The following transaction covers any possible database side-effects of the
|
214
425
|
# attributes assignment. For example, setting the IDs of a child collection.
|
215
426
|
with_transaction_returning_status do
|
216
|
-
|
427
|
+
assign_attributes(attributes)
|
217
428
|
save
|
218
429
|
end
|
219
430
|
end
|
220
431
|
|
221
|
-
|
222
|
-
|
223
|
-
|
432
|
+
alias update_attributes update
|
433
|
+
|
434
|
+
# Updates its receiver just like #update but calls #save! instead
|
435
|
+
# of +save+, so an exception is raised if the record is invalid and saving will fail.
|
436
|
+
def update!(attributes)
|
224
437
|
# The following transaction covers any possible database side-effects of the
|
225
438
|
# attributes assignment. For example, setting the IDs of a child collection.
|
226
439
|
with_transaction_returning_status do
|
227
|
-
|
440
|
+
assign_attributes(attributes)
|
228
441
|
save!
|
229
442
|
end
|
230
443
|
end
|
231
444
|
|
445
|
+
alias update_attributes! update!
|
446
|
+
|
447
|
+
# Equivalent to <code>update_columns(name => value)</code>.
|
448
|
+
def update_column(name, value)
|
449
|
+
update_columns(name => value)
|
450
|
+
end
|
451
|
+
|
452
|
+
# Updates the attributes directly in the database issuing an UPDATE SQL
|
453
|
+
# statement and sets them in the receiver:
|
454
|
+
#
|
455
|
+
# user.update_columns(last_request_at: Time.current)
|
456
|
+
#
|
457
|
+
# This is the fastest way to update attributes because it goes straight to
|
458
|
+
# the database, but take into account that in consequence the regular update
|
459
|
+
# procedures are totally bypassed. In particular:
|
460
|
+
#
|
461
|
+
# * \Validations are skipped.
|
462
|
+
# * \Callbacks are skipped.
|
463
|
+
# * +updated_at+/+updated_on+ are not updated.
|
464
|
+
# * However, attributes are serialized with the same rules as ActiveRecord::Relation#update_all
|
465
|
+
#
|
466
|
+
# This method raises an ActiveRecord::ActiveRecordError when called on new
|
467
|
+
# objects, or when at least one of the attributes is marked as readonly.
|
468
|
+
def update_columns(attributes)
|
469
|
+
raise ActiveRecordError, "cannot update a new record" if new_record?
|
470
|
+
raise ActiveRecordError, "cannot update a destroyed record" if destroyed?
|
471
|
+
|
472
|
+
attributes.each_key do |key|
|
473
|
+
verify_readonly_attribute(key.to_s)
|
474
|
+
end
|
475
|
+
|
476
|
+
id_in_database = self.id_in_database
|
477
|
+
attributes.each do |k, v|
|
478
|
+
write_attribute_without_type_cast(k, v)
|
479
|
+
end
|
480
|
+
|
481
|
+
affected_rows = self.class._update_record(
|
482
|
+
attributes,
|
483
|
+
self.class.primary_key => id_in_database
|
484
|
+
)
|
485
|
+
|
486
|
+
affected_rows == 1
|
487
|
+
end
|
488
|
+
|
232
489
|
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
|
233
490
|
# The increment is performed directly on the underlying attribute, no setter is invoked.
|
234
491
|
# Only makes sense for number-based attributes. Returns +self+.
|
@@ -238,102 +495,175 @@ module ActiveRecord
|
|
238
495
|
self
|
239
496
|
end
|
240
497
|
|
241
|
-
# Wrapper around
|
242
|
-
#
|
243
|
-
#
|
244
|
-
#
|
245
|
-
|
246
|
-
|
498
|
+
# Wrapper around #increment that writes the update to the database.
|
499
|
+
# Only +attribute+ is updated; the record itself is not saved.
|
500
|
+
# This means that any other modified attributes will still be dirty.
|
501
|
+
# Validations and callbacks are skipped. Supports the +touch+ option from
|
502
|
+
# +update_counters+, see that for more.
|
503
|
+
# Returns +self+.
|
504
|
+
def increment!(attribute, by = 1, touch: nil)
|
505
|
+
increment(attribute, by)
|
506
|
+
change = public_send(attribute) - (attribute_in_database(attribute.to_s) || 0)
|
507
|
+
self.class.update_counters(id, attribute => change, touch: touch)
|
508
|
+
clear_attribute_change(attribute) # eww
|
509
|
+
self
|
247
510
|
end
|
248
511
|
|
249
512
|
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
|
250
513
|
# The decrement is performed directly on the underlying attribute, no setter is invoked.
|
251
514
|
# Only makes sense for number-based attributes. Returns +self+.
|
252
515
|
def decrement(attribute, by = 1)
|
253
|
-
|
254
|
-
self[attribute] -= by
|
255
|
-
self
|
516
|
+
increment(attribute, -by)
|
256
517
|
end
|
257
518
|
|
258
|
-
# Wrapper around
|
259
|
-
#
|
260
|
-
#
|
261
|
-
#
|
262
|
-
|
263
|
-
|
519
|
+
# Wrapper around #decrement that writes the update to the database.
|
520
|
+
# Only +attribute+ is updated; the record itself is not saved.
|
521
|
+
# This means that any other modified attributes will still be dirty.
|
522
|
+
# Validations and callbacks are skipped. Supports the +touch+ option from
|
523
|
+
# +update_counters+, see that for more.
|
524
|
+
# Returns +self+.
|
525
|
+
def decrement!(attribute, by = 1, touch: nil)
|
526
|
+
increment!(attribute, -by, touch: touch)
|
264
527
|
end
|
265
528
|
|
266
529
|
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
|
267
530
|
# if the predicate returns +true+ the attribute will become +false+. This
|
268
531
|
# method toggles directly the underlying value without calling any setter.
|
269
532
|
# Returns +self+.
|
533
|
+
#
|
534
|
+
# Example:
|
535
|
+
#
|
536
|
+
# user = User.first
|
537
|
+
# user.banned? # => false
|
538
|
+
# user.toggle(:banned)
|
539
|
+
# user.banned? # => true
|
540
|
+
#
|
270
541
|
def toggle(attribute)
|
271
|
-
self[attribute] = !
|
542
|
+
self[attribute] = !public_send("#{attribute}?")
|
272
543
|
self
|
273
544
|
end
|
274
545
|
|
275
|
-
# Wrapper around
|
276
|
-
# its non-bang version in that it passes through the attribute setter.
|
546
|
+
# Wrapper around #toggle that saves the record. This method differs from
|
547
|
+
# its non-bang version in the sense that it passes through the attribute setter.
|
277
548
|
# Saving is not subjected to validation checks. Returns +true+ if the
|
278
549
|
# record could be saved.
|
279
550
|
def toggle!(attribute)
|
280
551
|
toggle(attribute).update_attribute(attribute, self[attribute])
|
281
552
|
end
|
282
553
|
|
283
|
-
# Reloads the
|
284
|
-
#
|
285
|
-
#
|
286
|
-
#
|
554
|
+
# Reloads the record from the database.
|
555
|
+
#
|
556
|
+
# This method finds the record by its primary key (which could be assigned
|
557
|
+
# manually) and modifies the receiver in-place:
|
558
|
+
#
|
559
|
+
# account = Account.new
|
560
|
+
# # => #<Account id: nil, email: nil>
|
561
|
+
# account.id = 1
|
562
|
+
# account.reload
|
563
|
+
# # Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]]
|
564
|
+
# # => #<Account id: 1, email: 'account@example.com'>
|
565
|
+
#
|
566
|
+
# Attributes are reloaded from the database, and caches busted, in
|
567
|
+
# particular the associations cache and the QueryCache.
|
568
|
+
#
|
569
|
+
# If the record no longer exists in the database ActiveRecord::RecordNotFound
|
570
|
+
# is raised. Otherwise, in addition to the in-place modification the method
|
571
|
+
# returns +self+ for convenience.
|
572
|
+
#
|
573
|
+
# The optional <tt>:lock</tt> flag option allows you to lock the reloaded record:
|
574
|
+
#
|
575
|
+
# reload(lock: true) # reload with pessimistic locking
|
576
|
+
#
|
577
|
+
# Reloading is commonly used in test suites to test something is actually
|
578
|
+
# written to the database, or when some action modifies the corresponding
|
579
|
+
# row in the database but not the object in memory:
|
580
|
+
#
|
581
|
+
# assert account.deposit!(25)
|
582
|
+
# assert_equal 25, account.credit # check it is updated in memory
|
583
|
+
# assert_equal 25, account.reload.credit # check it is also persisted
|
584
|
+
#
|
585
|
+
# Another common use case is optimistic locking handling:
|
586
|
+
#
|
587
|
+
# def with_optimistic_retry
|
588
|
+
# begin
|
589
|
+
# yield
|
590
|
+
# rescue ActiveRecord::StaleObjectError
|
591
|
+
# begin
|
592
|
+
# # Reload lock_version in particular.
|
593
|
+
# reload
|
594
|
+
# rescue ActiveRecord::RecordNotFound
|
595
|
+
# # If the record is gone there is nothing to do.
|
596
|
+
# else
|
597
|
+
# retry
|
598
|
+
# end
|
599
|
+
# end
|
600
|
+
# end
|
601
|
+
#
|
287
602
|
def reload(options = nil)
|
288
|
-
|
289
|
-
clear_association_cache
|
603
|
+
self.class.connection.clear_query_cache
|
290
604
|
|
291
|
-
|
292
|
-
|
293
|
-
|
294
|
-
|
605
|
+
fresh_object =
|
606
|
+
if options && options[:lock]
|
607
|
+
self.class.unscoped { self.class.lock(options[:lock]).find(id) }
|
608
|
+
else
|
609
|
+
self.class.unscoped { self.class.find(id) }
|
610
|
+
end
|
295
611
|
|
296
|
-
@
|
612
|
+
@attributes = fresh_object.instance_variable_get("@attributes")
|
613
|
+
@new_record = false
|
297
614
|
self
|
298
615
|
end
|
299
616
|
|
300
|
-
# Saves the record with the updated_at/on attributes set to the current time
|
301
|
-
#
|
302
|
-
#
|
303
|
-
#
|
617
|
+
# Saves the record with the updated_at/on attributes set to the current time
|
618
|
+
# or the time specified.
|
619
|
+
# Please note that no validation is performed and only the +after_touch+,
|
620
|
+
# +after_commit+ and +after_rollback+ callbacks are executed.
|
304
621
|
#
|
305
|
-
#
|
306
|
-
#
|
622
|
+
# This method can be passed attribute names and an optional time argument.
|
623
|
+
# If attribute names are passed, they are updated along with updated_at/on
|
624
|
+
# attributes. If no time argument is passed, the current time is used as default.
|
307
625
|
#
|
308
|
-
#
|
626
|
+
# product.touch # updates updated_at/on with current time
|
627
|
+
# product.touch(time: Time.new(2015, 2, 16, 0, 0, 0)) # updates updated_at/on with specified time
|
628
|
+
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
|
629
|
+
# product.touch(:started_at, :ended_at) # updates started_at, ended_at and updated_at/on attributes
|
630
|
+
#
|
631
|
+
# If used along with {belongs_to}[rdoc-ref:Associations::ClassMethods#belongs_to]
|
632
|
+
# then +touch+ will invoke +touch+ method on associated object.
|
309
633
|
#
|
310
634
|
# class Brake < ActiveRecord::Base
|
311
|
-
# belongs_to :car, :
|
635
|
+
# belongs_to :car, touch: true
|
312
636
|
# end
|
313
637
|
#
|
314
638
|
# class Car < ActiveRecord::Base
|
315
|
-
# belongs_to :corporation, :
|
639
|
+
# belongs_to :corporation, touch: true
|
316
640
|
# end
|
317
641
|
#
|
318
642
|
# # triggers @brake.car.touch and @brake.car.corporation.touch
|
319
643
|
# @brake.touch
|
320
|
-
|
321
|
-
|
322
|
-
|
323
|
-
|
324
|
-
|
325
|
-
|
326
|
-
|
327
|
-
|
328
|
-
|
329
|
-
|
330
|
-
|
644
|
+
#
|
645
|
+
# Note that +touch+ must be used on a persisted object, or else an
|
646
|
+
# ActiveRecordError will be thrown. For example:
|
647
|
+
#
|
648
|
+
# ball = Ball.new
|
649
|
+
# ball.touch(:updated_at) # => raises ActiveRecordError
|
650
|
+
#
|
651
|
+
def touch(*names, time: nil)
|
652
|
+
unless persisted?
|
653
|
+
raise ActiveRecordError, <<-MSG.squish
|
654
|
+
cannot touch on a new or destroyed record object. Consider using
|
655
|
+
persisted?, new_record?, or destroyed? before touching
|
656
|
+
MSG
|
657
|
+
end
|
331
658
|
|
332
|
-
|
659
|
+
attribute_names = timestamp_attributes_for_update_in_model
|
660
|
+
attribute_names |= names.map(&:to_s)
|
333
661
|
|
334
|
-
|
335
|
-
|
336
|
-
|
662
|
+
unless attribute_names.empty?
|
663
|
+
affected_rows = _touch_row(attribute_names, time)
|
664
|
+
@_trigger_update_callback = affected_rows == 1
|
665
|
+
else
|
666
|
+
true
|
337
667
|
end
|
338
668
|
end
|
339
669
|
|
@@ -343,34 +673,91 @@ module ActiveRecord
|
|
343
673
|
def destroy_associations
|
344
674
|
end
|
345
675
|
|
346
|
-
def
|
347
|
-
|
348
|
-
|
676
|
+
def destroy_row
|
677
|
+
_delete_row
|
678
|
+
end
|
679
|
+
|
680
|
+
def _delete_row
|
681
|
+
self.class._delete_record(self.class.primary_key => id_in_database)
|
682
|
+
end
|
683
|
+
|
684
|
+
def _touch_row(attribute_names, time)
|
685
|
+
time ||= current_time_from_proper_timezone
|
686
|
+
|
687
|
+
attribute_names.each do |attr_name|
|
688
|
+
write_attribute(attr_name, time)
|
689
|
+
clear_attribute_change(attr_name)
|
690
|
+
end
|
691
|
+
|
692
|
+
_update_row(attribute_names, "touch")
|
693
|
+
end
|
694
|
+
|
695
|
+
def _update_row(attribute_names, attempted_action = "update")
|
696
|
+
self.class._update_record(
|
697
|
+
attributes_with_values(attribute_names),
|
698
|
+
self.class.primary_key => id_in_database
|
699
|
+
)
|
700
|
+
end
|
701
|
+
|
702
|
+
def create_or_update(*args, &block)
|
703
|
+
_raise_readonly_record_error if readonly?
|
704
|
+
return false if destroyed?
|
705
|
+
result = new_record? ? _create_record(&block) : _update_record(*args, &block)
|
349
706
|
result != false
|
350
707
|
end
|
351
708
|
|
352
709
|
# Updates the associated record with values matching those of the instance attributes.
|
353
710
|
# Returns the number of affected rows.
|
354
|
-
def
|
355
|
-
|
356
|
-
|
357
|
-
|
358
|
-
|
359
|
-
|
711
|
+
def _update_record(attribute_names = self.attribute_names)
|
712
|
+
attribute_names &= self.class.column_names
|
713
|
+
attribute_names = attributes_for_update(attribute_names)
|
714
|
+
|
715
|
+
if attribute_names.empty?
|
716
|
+
affected_rows = 0
|
717
|
+
@_trigger_update_callback = true
|
718
|
+
else
|
719
|
+
affected_rows = _update_row(attribute_names)
|
720
|
+
@_trigger_update_callback = affected_rows == 1
|
721
|
+
end
|
722
|
+
|
723
|
+
yield(self) if block_given?
|
724
|
+
|
725
|
+
affected_rows
|
360
726
|
end
|
361
727
|
|
362
728
|
# Creates a record with values matching those of the instance attributes
|
363
729
|
# and returns its id.
|
364
|
-
def
|
365
|
-
|
366
|
-
|
367
|
-
new_id = self.class.unscoped.insert attributes_values
|
730
|
+
def _create_record(attribute_names = self.attribute_names)
|
731
|
+
attribute_names &= self.class.column_names
|
732
|
+
attributes_values = attributes_with_values_for_create(attribute_names)
|
368
733
|
|
734
|
+
new_id = self.class._insert_record(attributes_values)
|
369
735
|
self.id ||= new_id if self.class.primary_key
|
370
736
|
|
371
|
-
IdentityMap.add(self) if IdentityMap.enabled?
|
372
737
|
@new_record = false
|
738
|
+
|
739
|
+
yield(self) if block_given?
|
740
|
+
|
373
741
|
id
|
374
742
|
end
|
743
|
+
|
744
|
+
def verify_readonly_attribute(name)
|
745
|
+
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
|
746
|
+
end
|
747
|
+
|
748
|
+
def _raise_record_not_destroyed
|
749
|
+
@_association_destroy_exception ||= nil
|
750
|
+
raise @_association_destroy_exception || RecordNotDestroyed.new("Failed to destroy the record", self)
|
751
|
+
ensure
|
752
|
+
@_association_destroy_exception = nil
|
753
|
+
end
|
754
|
+
|
755
|
+
def belongs_to_touch_method
|
756
|
+
:touch
|
757
|
+
end
|
758
|
+
|
759
|
+
def _raise_readonly_record_error
|
760
|
+
raise ReadOnlyRecord, "#{self.class} is marked as readonly"
|
761
|
+
end
|
375
762
|
end
|
376
763
|
end
|