From 86d5c728fbbce6ba8ae73f8926084f5c0eee9a41 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 10 Jul 2010 00:50:59 +0200 Subject: revises recent commit related to :uniq => true --- railties/guides/source/association_basics.textile | 50 ++++++++++------------- 1 file changed, 22 insertions(+), 28 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index bc08874a30..aec1b0732d 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -1371,47 +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. It only works with +:through+ option. +Set the +:uniq+ option to true to keep the collection free of duplicates. This is mostly useful together with the +: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 + 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 # => [#, #] +Reading.all.inspect # => [#, #] -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. +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 add +uniq => true+ option. +Now let's set +:uniq+ to true: 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 + 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 # => [#] +Reading.all.inspect # => [#, #] -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. +In the above case there are still two readings. However +person.posts+ shows only one post because collection loads only unique records. h6(#has_many-validate). +:validate+ -- cgit v1.2.3