diff options
author | James Doyley <jdoyley@gmail.com> | 2015-11-24 15:02:23 +0000 |
---|---|---|
committer | James Doyley <jdoyley@gmail.com> | 2016-01-18 10:08:43 +0000 |
commit | f72fe2d5a65002195c15a0cfe3ae3c51db825d36 (patch) | |
tree | d9454561feae4cf4d17eb98d0872196916833963 /guides | |
parent | 58cea7f2dc7426c3f7445adfb8925880ec1b3644 (diff) | |
download | rails-f72fe2d5a65002195c15a0cfe3ae3c51db825d36.tar.gz rails-f72fe2d5a65002195c15a0cfe3ae3c51db825d36.tar.bz2 rails-f72fe2d5a65002195c15a0cfe3ae3c51db825d36.zip |
Updated the guides for having a distinct has_many through at the database level
The current example
add_index :person_articles, :article, unique: true
Does not work, the `:article` column does not exist as it will be
a join table (based on the prior example) so should use :article_id
The documentation seems to suggest that it will allow an article to
be added only once to a person via the join table, what actually
occurs is that it only allows the article to be added to one person,
at which point it should be a `belongs_to` association.
Also changed the new example to use readings based on the prior example
Diffstat (limited to 'guides')
-rw-r--r-- | guides/source/association_basics.md | 16 |
1 files changed, 13 insertions, 3 deletions
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index c272daac28..2e485b9932 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -1872,11 +1872,21 @@ If you want to make sure that, upon insertion, all of the records in the persisted association are distinct (so that you can be sure that when you inspect the association that you will never find duplicate records), you should add a unique index on the table itself. For example, if you have a table named -`person_articles` and you want to make sure all the articles are unique, you could -add the following in a migration: +`readings` and you want to make sure the articles can only be added to a person once, +you could add the following in a migration: ```ruby -add_index :person_articles, :article, unique: true +add_index :readings, [:person_id, :article_id], unique: true +``` + +Once you have this unique index, attempting to add the article to a person twice +will raise an `ActiveRecord::RecordNotUnique` error: + +```ruby +person = Person.create(name: 'Honda') +article = Article.create(name: 'a1') +person.articles << article +person.articles << article # => ActiveRecord::RecordNotUnique ``` Note that checking for uniqueness using something like `include?` is subject |