Commit Graph

188 Commits

Author SHA1 Message Date
Collin Jilbert
696ed4ebdd update return values to reflect the proper object class 2022-12-12 21:11:08 -06:00
George Claghorn
725ee79971 Allow resetting singular associations 2022-11-23 14:53:36 -05:00
Ali Deishidi
c13856e477
Reference consistency check correction (#45840)
* Reference consistency check correction 

By default all belongs_to relations are set to required, and required means Rails checks the reference consistency. That sentence is correct only if the optional is set to true, then in this case Rails not only allows this field to be null but also it does not check the reference consistency. But this is not the default behavior.

Co-authored-by: Eileen M. Uchitelle <eileencodes@users.noreply.github.com>
2022-08-18 08:51:11 -04:00
Andrey Sobolev
1018a5a7fb Fix typo in guide for scopes for has_and_belongs_to_many association 2022-02-15 17:27:11 +03:00
Jonathan Hefner
c7303ccc31 Link config settings to the configuration guide [ci-skip]
Since #43138, each config setting has its own linkable section in the
configuration guide.

This commit links config settings throughout the guides to their
sections in the configuration guide.
2022-02-13 13:13:11 -06:00
Jonathan Hefner
2189d97a2a
Merge pull request #44232 from khasinski/update-docs-for-counter-cache-caveats
Add note in guide for a counter cache caveat [ci skip]
2022-01-22 12:40:52 -06:00
Krzysztof Hasiński
ea2226605a Add a note in guide for a counter cache caveat
Counter cache can hold stale value if user changes primary key's value.
This caveat is not mentioned in guides, but according to #16159
comments it should be.
2022-01-22 19:32:56 +01:00
Daniel Colson
9e4b3f4e9e
Expand bi-directional associations guide [ci skip]
I remember being confused about what exactly association inverses would
do for me. This guide helped, but it leaves out some use cases. I'm hoping
that having all these use cases documented in one place with code
examples for each will make it easier for folks to understand why
they might want to set `:inverse_of` when Rails can't infer it.

Specifically, this commit:

* Adds an example explicitly demonstrating that all the `Author` objects
  are the same, and that no additional queries are executed.
* Preserves the example around preventing inconsistent data (although
  replaces the single-letter variable names)
* Adds an example around autosaving, which I'm not sure is explicitly
  documented elsewhere
* Adds an example around validations, linking to the relevant sections
  of the validation guide where we mention needing to set the
`:inverse_of` for these validations

This commit also adds links from the `:inverse_of` sections back up to
the Bi-directional associations sections, hopefully making those
`:inverse_of` sections clearer.
2022-01-21 16:25:09 -05:00
Rafael Mendonça França
83d85b2207
Start Rails 7.1 development 2021-12-07 15:52:30 +00:00
Juanito Fatas
1ef5ffef0a [ci skip] Fix link to Primary key 2021-11-11 23:54:51 +09:00
Daniel Colson
518b9a301f
Automatically infer inverse_of with scopes
Background
---

I recently noticed we had a number of associations in GitHub that would
benefit from having `inverse_of` set, and so I began adding them. I
ended up adding them to virtually every association with a scope, at
which point I wondered whether Rails might be able to automatically find
these inverses for us.

For GitHub, the changes in this commit end up automatically adding
`inverse_of` to 171 of associations that were missing it.

My understanding is that we do not automatically detect `inverse_of` for
associations with scopes because the scopes could exclude the records we
are trying to inverse from. But I think that should only matter if there
is a scope on the inverse side, not on the association itself.

For example:

Scope on has_many
----

```rb
class Post < ActiveRecord::Base
  has_many :comments, -> { visible }
end

class Comment < ActiveRecord::Base
  belongs_to :post

  scope :visible, -> { where(visible: true) }
  scope :hidden, -> { where(visible: false) }
end

post = Post.create!
comment = post.comments.hidden.create!
assert comment.post
```

This code leaves `post.comments` in sort of a weird state, since it
includes a comment that the association would filter out. But that's
true regardless of the changes in this commit.

Regardless of whether the comments association has an inverse,
`comment.post` will return the post. The difference is that when
`inverse_of` is set we use the existing post we have in memory, rather
than loading it again. If there is a downside to having the `inverse_of`
automatically set here I'm not seeing it.

Scope on belongs_to
----

```rb
class Post < ActiveRecord::Base
  has_many :comments

  scope :visible, -> { where(visible: true) }
  scope :hidden, -> { where(visible: false) }
end

class Comment < ActiveRecord::Base
  belongs_to :post, -> { visible }
end

post = Post.hidden.create!
comment = post.comments.create!
assert_nil comment.post
```

This example is a different story. We don't want to automatically infer
the inverse here because that would change the behavior of
`comment.post`. It should return `nil`, since it's scoped to visible
posts while this one is hidden.

This behavior was not well tested, so this commit adds a test to
ensure we haven't changed it.

Changes
---

This commit changes `can_find_inverse_of_automatically` to allow us to
automatically detect `inverse_of` when there is a scope on the
association, but not when there is a scope on the potential inverse
association. (`can_find_inverse_of_automatically` gets called first with
the association's reflection, then if it returns true we attempt to find
the inverse reflection, and finally we call the method again with the
inverse reflection to ensure we can really use it.)

Since this is a breaking change—specifically in places where code may
have relied on a missing `inverse_of` causing fresh copies of a record
to be loaded—we've placed it behind the `automatic_scope_inversing` flag
(whose name was inspired by `has_many_inversing`). It is set to true for
new applications via framework defaults.

Testing
---

In addition to the inverse association tests, this commit also adds some
cases to a few tests related to preloading. They are basically
duplicates of existing tests, but with lower query counts.

Testing this change with GitHub, the bulk of the failing tests were
related to lower query counts. There were additionally 3 places (2 in
tests and one in application code) where we relied on missing
`inverse_of` causing fresh copies of a record to be loaded.

There's still one Rails test that wouldn't pass if we ran the whole
suite with `automatic_scope_inversing = true`. It's related to
`TaggedPost`, which changes the polymorphic type from the base class
`Post` to the subclass `TaggedPost`.

```rb
class TaggedPost < Post
  has_many :taggings, -> { rewhere(taggable_type: "TaggedPost") }, as: :taggable
end
```

Setting the inverse doesn't work because it ends up changing the type
back to `Post`, something like this:

```rb
post = TaggedPost.new
tagging = post.taggings.new
puts tagging.taggable_type
=> TaggedPost

tagging.taggable = post
puts tagging.taggable_type
=> Post
```

I think this is an acceptable change, given that it's a fairly specific
scenario, and is sort of at odds with the way polymorphic associations
are meant to work (they are meant to contain the base class, not the
subclass). If someone is relying on this specific behavior they can
still either keep `automatic_scope_inversing` set to false, or they can
add `inverse_of: false` to the association.

I haven't found any other cases where having the `inverse_of` would
cause problems like this.

Co-authored-by: Chris Bloom <chrisbloom7@gmail.com>
2021-10-04 09:42:04 -04:00
George Claghorn
fc3acf2e8d Add change tracking methods for belongs_to associations
Permit checking whether a belongs_to association has been pointed to a new target record in the previous save and whether it will point to a new target record in the next save.

    post.category # => #<Category id: 1, name: "Ruby">

    post.category = Category.second   # => #<Category id: 2, name: "Programming">
    post.category_changed?            # => true
    post.category_previously_changed? # => false

    post.save!

    post.category_changed?            # => false
    post.category_previously_changed? # => true
2021-07-19 14:39:13 -04:00
Ryuta Kamizono
35bf079aed Update all Migration version references
Migration version references has been updated 2 times in less than 3
weeks (#41894, #42113).

I'd not want to receive the same tweaks in the near future.
2021-05-02 21:17:04 +09:00
John Bampton
debab67a85 Lint Markdown blank lines around headings [ci-skip] 2021-04-14 01:17:46 +10:00
Ryuta Kamizono
af4ca424eb Follow up to #41765 [ci skip] 2021-03-28 10:55:35 +09:00
Jason Barnabe
345384fb1f
Specifiy association :validate option only applies to new associated objects
Per [code comments](6daa2d8315/activerecord/lib/active_record/associations.rb (L1418-L1420)), the `:validate` option only makes a difference for *new* objects. Existing objects are not validated, regardless of the setting.
2021-03-25 15:04:45 -05:00
Cory Gwin
96b3d5a026
Document Destroy Async (#41680)
* Document Destroy Async
Motivation:
  - Add docs for Destroy async. I think I probably need to add
    information about setting up active job, but I am not sure where we
    want this, so I am putting this together to start conversation.

Related Issues:
  - #41093

* Active Job not ActiveJob

* Fix some spelling issues

[Cory Gwin, Rafael Mendonça França, Eileen M. Uchitelle, Henrik Nyh]
2021-03-24 00:54:50 -04:00
Jonathan Hefner
cb0da4f817 Fix typos, grammar, and formatting [ci-skip]
This is a collection of minor superficial improvements.  It does not
include any significant content changes.
2020-12-28 12:05:53 -06:00
Jonathan Hefner
27786c8d1e Normalize code indentation [ci-skip]
This removes unnecessary indentation of several code snippets, and
otherwise normalizes indentation of a handful more.
2020-12-25 21:17:50 -06:00
Jonathan Hefner
f3f36e7ef7 Fix syntax highlighting [ci-skip]
This fixes the syntax highlighting of several code snippets by changing
the code fences to the correct language.
2020-12-25 21:03:11 -06:00
Ryuta Kamizono
870f9dfacb
Merge pull request #40320 from mh-mobile/master
[skip ci]  Fix examples for has_{one,many} :through :source and :source_type
2020-11-25 21:45:08 +09:00
Jonathan Hefner
661fb798d2 Link to API docs in AR Associations guide [ci-skip]
This links the first mention of each method to its API documentation,
similar to a Wikipedia article.  Some subsequent mentions are also
linked, when it suits the surrounding text.
2020-11-07 15:02:26 -06:00
Jonathan Hefner
3c9d7a268f Use irb code fences where applicable [ci-skip]
Using `irb` code fences and the appropriate prompt syntax results in
better syntax highlighting.
2020-11-01 16:29:18 -06:00
mh-mobile
9d547ec8c2 Fix examples for has_{one,many} :through :source and :source_type 2020-10-02 22:03:12 +09:00
Alan Savage
262137441a Clarify exists? and find query only in the table 2020-09-02 22:07:36 -07:00
Sandip Mane
810f2a65c3 Added docs for habtm association about the declaring model referring to zero or more associations
parent f4471fc728d372861095d8f0a5b19831e316ead7
author Sandip Mane <sandip.mane@bigbinary.com> 1593247595 +0530
committer Sandip Mane <sandip2490@gmail.com> 1597253412 +0530

Adds doc for habtm association for always optional: true

Added docs line under definition of habtm with a text containing habtm refers to zero or more associations

Added docs line under definition of habtm with a text containing it refers to zero or more associations

Updated the sentence to include declaring association for habtm relation
2020-08-12 23:01:00 +05:30
Victor Perez Rodriguez
91daacbbda fix misleading section on associations guide 2020-07-07 00:18:50 -05:00
Dr Nic Williams
b6afb3df70
[guide][association_basics] Fix grammar for a single example
The original text indicated that 3 examples were forthcoming, yet alas only on `Car` model was created. No `Bike` nor `Bus`. I've reworded the text so that the reader is not left in suspense for the missing examples.
2020-06-22 12:08:10 +10:00
Vipul A M
e07d10d583 Expand on specs of self join and add make doc changes to suggest users to also do foreign_key when doing self join 2020-06-05 01:09:50 +05:30
Jonathan Hefner
27cf6eced8
Merge pull request #39193 from p8/guides/association-callbacks-with-throw
Association callbacks work with abort instead of exceptions [ci skip]
2020-05-09 02:58:14 -05:00
Petrik
6b05b50440 Association callbacks work with abort instead of exceptions [ci skip]
To prevent an object from being added/removed from an association an
abort must be thrown, not an Exception.
2020-05-09 09:37:01 +02:00
Jonathan Hefner
12493dc288
Fix typo [ci skip]
"it's" => "its"
2020-05-07 00:10:15 -05:00
Vasily Fedoseyev
56aa002961 Clarify that belongs_to is not always a one-to-one relation [skip ci] 2020-03-26 17:29:46 +03:00
davidauza-engineer
12719f9d6a Update Migration number to ensure consistency on the documentation [ci skip]
Updated Migration number to 6.0 as there were cases where it did show 5.0 and 5.2 which may lead to confusion on a newcomer reader.
2020-01-25 15:12:33 -05:00
Haroon Ahmed
db1ae8cbb4 remove reference to global rails command and replace with bin/rails 2019-12-27 19:32:37 +00:00
Kevin Jacoby
b0743dda8c Clarify documentation by removing charged words
Using words such as 'just', 'simply' and 'easy' implies to the reader
that the tasks they are trying to accomplish are tasks that anyone can
do, which might then frustrate them if they find it difficult to
complete.

This commit rephrases some usage of these words to aid understanding in
the readers without making them feel belittled.

[ci skip]
2019-12-12 19:43:51 +00:00
Vishal Telangre
8092b3c1ee
[skip ci] Add undefined STI acronym to the heading which is referred under its section 2019-05-12 20:49:54 +05:30
Abhay Nikam
71b5664432 Adds documentation for has_one touch option after #35869 [ci skip] 2019-04-25 08:06:16 +05:30
lxxxvi
cdaa4baecc change t.integer to t.bigint where applicable 2019-04-07 11:35:45 +02:00
Tim Wade
af56c5c1c6 [skip ci] Add examples for has_{one,many} :through :source and :source_type (#35612)
* Add example for has_many :through source/source_type

* Add example for has_one :through source/source_type
2019-04-03 13:05:20 -04:00
Rodrigo
7515afcbbd Add note about has_many associations callbacks [ci skip]
Add a note explaining when the has_many associations callbacks will be called or not.
2019-03-12 10:28:31 +00:00
Nathaniel Suchy
d9f1cc05b5 Update links and code examples in the guides to use HTTPS where the host supports it. 2019-03-06 15:21:07 -05:00
Laerti
41ffddbc8b Refs #28025 nullify *_type column on polymorphic associations on :nu… (#28078)
This PR addresses the issue described in #28025. On `dependent: :nullify` strategy only the foreign key of the relation is nullified. However on polymorphic associations the  `*_type` column is not nullified leaving the record with a NULL `*_id` but the `*_type` column is present.
2019-01-15 23:03:20 +09:00
Espartaco Palma
9b0b066ef7
fix typo on association_basics.md [ci skip] 2018-11-14 00:10:02 -08:00
Marcel M. Cary
39806b6d98 Describe how has_many's :dependent option affects #delete
I was puzzled about why `collection=` was destroying the removed
records on an association with `dependent: :destroy`, even after
consulting the documentation for that option.  I had to dive into the
Active Record source to understand what was going on: eventually
`collection=` calls `collection.delete` on the ousted records, and it
also uses the `:dependent` option to decide how to remove records.

It would have helped me to have mention of this in the documentation for
`:dependent`, not just under `collection.delete` (which I found much
later).

Briefly mention the broader impacts of `:dependent` in the Association
Basics guide.

[ci skip]
2018-11-13 16:06:00 -08:00
Malcolm Locke
20ea01bd64 Document exception from restrict_with_exception [ci skip] 2018-10-29 15:12:29 +13:00
Raghu Kamat
b2e74b36bf [ci skip] Fix #33914
This commit removes the dependent: :destroy option from the belong_to example since there is a warning associated with the usage of dependent: :destroy along with belongs_to. Based on the feedback on the issue #33914, I  replaced dependent: :destroy with touch: :books_updated_at which will make the example consistent with the example that already exists on that page.
 * Also Removing the touch option from the belong_to scopes example as the option doesnt have any relation to association scope.
2018-10-22 14:39:05 -04:00
Ryuta Kamizono
12c7b101f8 Remove and flip index: true for references in the doc [ci skip]
Follow up #32146.
2018-10-17 21:43:23 +09:00
Ryuta Kamizono
dbb5d57538
Merge pull request #32146 from abhikanojia/association_guide_fix
Remove index:true option from belongs to as defaults to true.

[ci skip]
2018-10-17 21:21:14 +09:00
Ian Fleeton
f0c161cc05 Replace line items with chapters [ci skip]
Line items are a holdover from when orders were used in the examples
instead of books.
2018-09-21 12:40:16 +01:00