aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/autosave_association.rb
Commit message (Collapse)AuthorAgeFilesLines
* Don't validate non dirty association targetsWill Jessop2019-07-151-1/+1
| | | | | | | | | | | | | | | | | Fixes #36581. This fixes an issue where validations would return differently when a previously saved invalid association was loaded between calls: assert_equal true, squeak.valid? assert_equal true, squeak.mouse.present? assert_equal true, squeak.valid? Here the second assert would return Expected: true Actual: false Limiting validations to associations that would be normally saved (using autosave: true) due to changes means that loading invalid associated relations will not change the return value of the parent relations's `valid?` method.
* Merge pull request #36210 from ↵Rafael França2019-06-241-1/+1
|\ | | | | | | | | vishaltelangre/raise-record-invalid-when-associations-fail-to-save-due-to-uniqueness-failure Fix: ActiveRecord::RecordInvalid is not raised when an associated record fails to #save! due to uniqueness validation failure
| * Fix: ActiveRecord::RecordInvalid is not raised when an associated record ↵Vishal Telangre2019-05-101-1/+1
| | | | | | | | | | | | | | | | fails to #save! due to uniqueness validation failure Add tests Fix tests failing due to introduction of uniquness rule added to Book model
* | Enable `Layout/EmptyLinesAroundAccessModifier` copRyuta Kamizono2019-06-131-2/+0
|/ | | | | | | | | | | We sometimes say "✂️ newline after `private`" in a code review (e.g. https://github.com/rails/rails/pull/18546#discussion_r23188776, https://github.com/rails/rails/pull/34832#discussion_r244847195). Now `Layout/EmptyLinesAroundAccessModifier` cop have new enforced style `EnforcedStyle: only_before` (https://github.com/rubocop-hq/rubocop/pull/7059). That cop and enforced style will reduce the our code review cost.
* Merge pull request #32313 from lulalala/model_error_as_objectRafael França2019-04-241-16/+9
|\ | | | | Model error as object
| * Allow errors to remove duplicates, and ensure cyclic associations w/ ↵lulalala2019-03-311-3/+1
| | | | | | | | | | autosave duplicate errors can be removed See SHA 7550f0a016ee6647aaa76c0c0ae30bebc3867288
| * Use errors#import instead of manipulating errors/details hashlulalala2019-03-311-13/+8
| |
* | Merge pull request #28155 from lcreid/belongs_toRyuta Kamizono2019-04-101-2/+6
|\ \ | |/ |/| | | Fix "autosave: true" on belongs_to of join model causes invalid records to be saved
| * Fix circular `autosave: true`Larry Reid2018-07-231-2/+6
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Use a variable local to the `save_collection_association` method in `activerecord/lib/active_record/autosave_association.rb`, instead of an instance variable. Prior to this PR, when there was a circular series of `autosave: true` associations, the callback for a `has_many` association was run while another instance of the same callback on the same association hadn't finished running. When control returned to the first instance of the callback, the instance variable had changed, and subsequent associated records weren't saved correctly. Specifically, the ID field for the `belongs_to` corresponding to the `has_many` was `nil`. Remove unnecessary test and comments. Fixes #28080.
* | Fix unintended autosave on has_one through associationSergiy Kukunin2019-03-221-1/+7
| | | | | | | | | | | | | | | | | | | | | | | | | | | | Fixes #35680 The problem occurred, when a `has one through` association contains a foreign key (it belongs to the intermediate association). For example, Comment belongs to Post, Post belongs to Author, and Author `has_one :first_comment, through: :first_post`. In this case, the value of the foreign key is comparing with the original record, and since they are likely different, the association is marked as changed. So it updates every time when the origin record updates.
* | Merge pull request #33378 from numbata/subclass-redefine-autosave-callbacksRafael Mendonça França2018-09-131-1/+1
|\ \ | | | | | | | | | Allow subclasses to redefine autosave callbacks for associated records
| * | Allow subclasses to redefine autosave callbacks for associated recordsAndrey Subbota2018-07-271-1/+1
| |/
* / Fix regression setting children record in parent before_save callback.Guo Xiang Tan2018-09-031-5/+5
|/
* Fix parent record should not get saved with duplicate children recordsSantosh Wadghule2018-05-281-3/+5
| | | | - Fixes #32940
* Rollback parent transaction when children fails to update (#32796)Guillaume Malette2018-05-221-2/+5
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Rollback parent transaction when children fails to update Rails supports autosave associations on the owner of a `has_many` relationship. In certain situation, if the children of the association fail to save, the parent is not rolled back. ```ruby class Employee < ActiveRecord::Base end class Company < ActiveRecord::Base has_many(:employees) end company = Company.new employee = company.employees.new company.save ``` In the previous example, if the Employee failed to save, the Company will not be rolled back. It will remain in the database with no associated Employee. I expect the `company.save` call to be atomic, and either create all or none of the records. The persistance of the Company already starts a transaction that nests it's children. However, it didn't track the success or failure of it's children in this very situation, and the outermost transaction is not rolled back. This PR makes the change to track the success of the child insertion and rollback the parent if any of the children fail. * Change the test to reflect what we expect Once #32862 is merged, rolling back a record will rollback it's state to match the state before the database changes were applied * Use only the public API to express the tests * Refactor to avoid reassigning saved for nested reflections [Guillaume Malette + Rafael Mendonça França]
* Inverse instance should not be reloaded during autosave if called in validationAnmol Chopra2017-11-271-0/+3
| | | | | Record saved in save_has_one_association already make call to association.loaded! via record's before_save callback of save_belongs_to_association, but this will reload object if accessed in record's validation.
* Use frozen-string-literal in ActiveRecordKir Shatrov2017-07-191-0/+2
|
* Revert "Merge pull request #29540 from kirs/rubocop-frozen-string"Matthew Draper2017-07-021-1/+0
| | | | | This reverts commit 3420a14590c0e6915d8b6c242887f74adb4120f9, reversing changes made to afb66a5a598ce4ac74ad84b125a5abf046dcf5aa.
* Enforce frozen string in RubocopKir Shatrov2017-07-011-0/+1
|
* Use mattr_accessor default: option throughout the projectGenadi Samokovarov2017-06-031-2/+1
|
* Merge pull request #29074 from ↵Kasper Timm Hansen2017-05-281-8/+1
|\ | | | | | | | | kamipo/remove_returning_true_in_internal_callbacks Remove returning true in internal callbacks
| * Remove returning true in internal callbacksRyuta Kamizono2017-05-141-8/+1
| | | | | | | | | | `display_deprecation_warning_for_false_terminator` was removed since 3a25cdc.
* | Remove unneeded `association.respond_to?(:reset_scope)`Ryuta Kamizono2017-05-171-1/+1
|/ | | | | Since 86390c3 all associations have `reset_scope` so `respond_to?` is unneeded.
* Don't attempt to create a new record that was already created.Isaac Betesh2017-04-201-0/+5
| | | | Fixes #24032
* `self.` is not needed when calling its own instance methodAkira Matsuda2017-01-051-2/+2
| | | | Actually, private methods cannot be called with `self.`, so it's not just redundant, it's a bad habit in Ruby
* Reload association scope inside autosaved associationsEdgars Beigarts2016-12-021-3/+3
|
* Deprecate the behavior of AR::Dirty inside of after_(create|update|save) ↵Sean Griffin2016-11-011-2/+2
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | callbacks We pretty frequently get bug reports that "dirty is broken inside of after callbacks". Intuitively they are correct. You'd expect `Model.after_save { puts changed? }; model.save` to do the same thing as `model.save; puts model.changed?`, but it does not. However, changing this goes much farther than just making the behavior more intuitive. There are a _ton_ of places inside of AR that can be drastically simplified with this change. Specifically, autosave associations, timestamps, touch, counter cache, and just about anything else in AR that works with callbacks have code to try to avoid "double save" bugs which we will be able to flat out remove with this change. We introduce two new sets of methods, both with names that are meant to be more explicit than dirty. The first set maintains the old behavior, and their names are meant to center that they are about changes that occurred during the save that just happened. They are equivalent to `previous_changes` when called outside of after callbacks, or once the deprecation cycle moves. The second set is the new behavior. Their names imply that they are talking about changes from the database representation. The fact that this is what we really care about became clear when looking at `BelongsTo.touch_record` when tests were failing. I'm unsure that this set of methods should be in the public API. Outside of after callbacks, they are equivalent to the existing methods on dirty. Dirty itself is not deprecated, nor are the methods inside of it. They will only emit the warning when called inside of after callbacks. The scope of this breakage is pretty large, but the migration path is simple. Given how much this can improve our codebase, and considering that it makes our API more intuitive, I think it's worth doing.
* Add more rubocop rules about whitespacesRafael Mendonça França2016-10-291-3/+3
|
* Always store errors details information with symbolsRafael Mendonça França2016-09-191-10/+12
| | | | | | | | | | | | | | | | | | When the association is autosaved we were storing the details with string keys. This was creating inconsistency with other details that are added using the `Errors#add` method. It was also inconsistent with the `Errors#messages` storage. To fix this inconsistency we are always storing with symbols. This will cause a small breaking change because in those cases the details could be accessed as strings keys but now it can not. The reason that we chose to do this breaking change is because `#details` should be considered a low level object like `#messages` is. Fix #26499. [Rafael Mendonça França + Marcus Vieira]
* Don't unnecessarily load a belongs_to when saving.James Coleman2016-08-261-1/+3
| | | | | | | | Previously, if the the association was previously loaded and then the foreign key changed by itself, a #save call would trigger a load of the new associated record during autosave. This is unnecessary and the autosave code (in that case) didn't use the loaded record anyways.
* modernizes hash syntax in activerecordXavier Noria2016-08-061-3/+3
|
* A small documentation fix about autosave associations [ci skip]Mehmet Emin İNAÇ2016-03-051-1/+1
|
* Fixed setting errors details on autosaved associationsWojciech Wnętrzak2015-10-281-3/+18
|
* Merge pull request #19686 from tsun1215/index_errorsSean Griffin2015-10-261-3/+9
|\ | | | | | | | | | | Errors can be indexed with nested attributes Close #8638
| * Errors can be indexed with nested attributesMichael Probber2015-04-171-3/+9
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | `has_many` can now take `index_errors: true` as an option. When this is enabled, errors for nested models will be returned alongside an index, as opposed to just the nested model name. This option can also be enabled (or disabled) globally through `ActiveRecord::Base.index_nested_attribute_errors` E.X. ```ruby class Guitar < ActiveRecord::Base has_many :tuning_pegs accepts_nested_attributes_for :tuning_pegs end class TuningPeg < ActiveRecord::Base belongs_to :guitar validates_numericality_of :pitch end ``` - Old style - `guitar.errors["tuning_pegs.pitch"] = ["is not a number"]` - New style (if defined globally, or set in has_many_relationship) - `guitar.errors["tuning_pegs[1].pitch"] = ["is not a number"]` [Michael Probber, Terence Sun]
* | applies new doc guidelines to Active Record.Yves Senn2015-10-141-5/+4
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The focus of this change is to make the API more accessible. References to method and classes should be linked to make it easy to navigate around. This patch makes exzessiv use of `rdoc-ref:` to provide more readable docs. This makes it possible to document `ActiveRecord::Base#save` even though the method is within a separate module `ActiveRecord::Persistence`. The goal here is to bring the API closer to the actual code that you would write. This commit only deals with Active Record. The other gems will be updated accordingly but in different commits. The pass through Active Record is not completely finished yet. A follow up commit will change the spots I haven't yet had the time to update. /cc @fxn
* | add missing `:nodoc:` for `AutosaveAssociation::ClassMethods` [ci skip]Yves Senn2015-10-141-1/+1
| |
* | Fix Punctuation in `AutosaveAssociation` RDocRobert Eshleman2015-08-201-2/+2
| | | | | | | | [ci skip]
* | Correctly ignore `mark_for_destruction` without `autosave`Sean Griffin2015-07-201-1/+1
| | | | | | | | | | | | | | | | | | As per the docs, `mark_for_destruction` should do nothing if `autosave` is not set to true. We normally persist associations on a record no matter what if the record is a new record, but we were always skipping records which were `marked_for_destruction?`. Fixes #20882
* | Ensure cyclic associations w/ autosave don't cause duplicate errorsSean Griffin2015-07-181-0/+7
|/ | | | | | | | | | | | | | | | This code is so fucked. Things that cause this bug not to replicate: - Defining the validation before the association (we end up calling `uniq!` on the errors in the autosave validation) - Adding `accepts_nested_attributes_for` (I have no clue why. The only thing it does that should affect this is adds `autosave: true` to the inverse reflection, and doing that manually doesn't fix this). This solution is a hack, and I'm almost certain there's a better way to go about it, but this shouldn't cause a huge hit on validation times, and is the simplest way to get it done. Fixes #20874.
* Always perform validations on nested attribute associationsSean Griffin2015-01-301-4/+12
| | | | | | | Collection associations would have already been validated, but singular associations were not. Fixes #18735.
* Fix potenital stack level too deep with autosave or validationMiklos Fazkeas2015-01-041-4/+11
| | | | | | | When associations checked for autosave have a cycle, and none of them is dirty, then changed_for_autosave? will be an infinite loop. We now remember if we're in the check and will short circuit the recursion.
* Deprecate `false` as the way to halt AR callbacksclaudiob2015-01-021-1/+1
| | | | | | | | | | Before this commit, returning `false` in an ActiveRecord `before_` callback such as `before_create` would halt the callback chain. After this commit, the behavior is deprecated: will still work until the next release of Rails but will also display a deprecation warning. The preferred way to halt a callback chain is to explicitly `throw(:abort)`.
* Deprecate `false` as the way to halt AS callbacksclaudiob2015-01-021-1/+7
| | | | | | | | | | | | | | After this commit, returning `false` in a callback will display a deprecation warning to make developers aware of the fact that they need to explicitly `throw(:abort)` if their intention is to halt a callback chain. This commit also patches two internal uses of AS::Callbacks (inside ActiveRecord and ActionDispatch) which sometimes return `false` but whose returned value is not meaningful for the purpose of execution. In both cases, the returned value is set to `true`, which does not affect the execution of the callbacks but prevents unrequested deprecation warnings from showing up.
* Pass symbol as an argument instead of a blockErik Michaels-Ober2014-11-291-3/+3
|
* Autosave callbacks shouldn't be `after_save`Agis-2014-10-131-1/+3
| | | | | | | | | | | | 068f092ced8483e557725542dd919ab7c516e567 registered autosave callbacks as `after_save` callbacks. This caused the regression described in #17209. Autosave callbacks should be registered as `after_update` and `after_create` callbacks, just like before. This is a partial revert of 068f092ced8483e557725542dd919ab7c516e567. Fixes #17209.
* Use has_attribute?Rafael Mendonça França2014-09-171-1/+1
|
* Don't autosave unchanged has_one through recordsAlan Kennedy2014-09-151-1/+3
|
* Do not mark object as persisted after an association is savedRafael Mendonça França2014-09-051-2/+0
| | | | | | | | | | | Callback order in Active Record objects are important. Users should not define callbacks before the association definition or surprising behaviours like the described at #3798 will happen. This callback order dependency is documented at https://github.com/rails/rails/blob/31bfcdc77ca0d8cec9b5fe513bdc6f05814dd4f1/activerecord/lib/active_record/associations.rb#L1222-1227. This reverts #15728. Fixes #16620.
* Don't save through records twiceSean Griffin2014-06-171-3/+2
| | | | | | | If the through record gets created in an `after_create` hook that is defined before the association is defined (therefore after its `after_create` hook) get saved twice. This ensures that the through records are created only once, regardless of the order of the hooks.