From 44b752bea148b9df8f4d806e410e30fff26f680e Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Fri, 9 Jul 2010 16:39:34 -0400 Subject: expanding on :uniq option in has_many --- activerecord/lib/active_record/associations.rb | 2 +- railties/guides/source/association_basics.textile | 42 ++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 65daa8ffbe..11555b88e0 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -889,7 +889,7 @@ module ActiveRecord # Specifies type of the source association used by has_many :through queries where the source # association is a polymorphic +belongs_to+. # [:uniq] - # If true, duplicates will be omitted from the collection. Useful in conjunction with :through. + # If true, duplicates will be omitted from the collection. Works only in conjunction with :through. # [:readonly] # If true, all the associated objects are readonly through the association. # [:validate] diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index c69f2ae8c9..bc08874a30 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -1371,7 +1371,47 @@ 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. +Specify the +:uniq => true+ option to remove duplicates from the collection. It only works with +:through+ option. + + +class Person < ActiveRecord::Base + has_many :readers + has_many :posts, :through => :readers + + def self.lab + person = Person.create(:name => 'john') + p = Post.create(:name => 'a1') + person.posts << p + person.posts << p + person.reload + puts person.posts.inspect #=> [#, #] + puts Reader.all.inspect #=> [#, #] + end +end + + +In the above case +readers+ table has two records and +person.posts+ brings out both of these records even though these records are basically pointing to the same +post+ record. + +Now let's add +uniq => true+ option. + + +class Person + has_many :readers + has_many :posts, :through => :readers, :uniq => true + + def self.experiment + person = Person.create(:name => 'honda') + p = Post.create(:name => 'a1') + person.posts << p + person.posts << p + person.reload + puts person.posts.inspect #=> [#] + puts Reader.all.inspect #=> [#, #] + end +end + + +In the above case +readers+ table still has two records. However +person.posts+ will show only one +post+ record because collection will load only +unique+ records. h6(#has_many-validate). +:validate+ -- cgit v1.2.3