aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/association_basics.textile
diff options
context:
space:
mode:
Diffstat (limited to 'railties/guides/source/association_basics.textile')
-rw-r--r--railties/guides/source/association_basics.textile36
1 files changed, 35 insertions, 1 deletions
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index c69f2ae8c9..b1ee4b8be4 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -1371,7 +1371,41 @@ The +:through+ option specifies a join model through which to perform the query.
h6(#has_many-uniq). +:uniq+
-Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
+Set the +:uniq+ option to true to keep the collection free of duplicates. This is mostly useful together with the +:through+ option.
+
+<ruby>
+class Person < ActiveRecord::Base
+ has_many :readings
+ has_many :posts, :through => :readings
+end
+
+person = Person.create(:name => 'john')
+post = Post.create(:name => 'a1')
+person.posts << post
+person.posts << post
+person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
+Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
+</ruby>
+
+In the above case there are two readings and +person.posts+ brings out both of them even though these records are pointing to the same post.
+
+Now let's set +:uniq+ to true:
+
+<ruby>
+class Person
+ has_many :readings
+ has_many :posts, :through => :readings, :uniq => true
+end
+
+person = Person.create(:name => 'honda')
+post = Post.create(:name => 'a1')
+person.posts << post
+person.posts << post
+person.posts.inspect # => [#<Post id: 7, name: "a1">]
+Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
+</ruby>
+
+In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records.
h6(#has_many-validate). +:validate+