From 64148ab96b47a9904fdd839bc69971b4e156bb04 Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Thu, 26 May 2011 22:19:10 -0400 Subject: Improve 'Joining Tables' section with additional examples and explanation. --- .../guides/source/active_record_querying.textile | 30 +++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 6cba34c7cd..0690b5e169 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -675,7 +675,7 @@ class Post < ActiveRecord::Base has_many :tags end -class Comments < ActiveRecord::Base +class Comment < ActiveRecord::Base belongs_to :post has_one :guest end @@ -683,6 +683,10 @@ end class Guest < ActiveRecord::Base belongs_to :comment end + +class Tag < ActiveRecord::Base + belongs_to :post +end Now all of the following will produce the expected join queries using +INNER JOIN+: @@ -700,6 +704,8 @@ SELECT categories.* FROM categories INNER JOIN posts ON posts.category_id = categories.id +Or, in English: "return a category object for all categories with posts". (You will see duplicate categories if more than one post has the same category. If you want unique posts, you can use Category.joins(:post).select("distinct(categories.id)).) + h5. Joining Multiple Associations @@ -714,18 +720,40 @@ SELECT posts.* FROM posts INNER JOIN comments ON comments.post_id = posts.id +Or, in English: "return all posts that have a category and at least one comment". Note again that posts with multiple comments will show up multiple times. + h5. Joining Nested Associations (Single Level) Post.joins(:comments => :guest) +This produces: + + +SELECT posts.* FROM posts + INNER JOIN comments ON comments.post_id = posts.id + INNER JOIN guests ON guests.comment_id = comments.id + + +Or, in English: "return all posts that have a comment made by a guest." + h5. Joining Nested Associations (Multiple Level) Category.joins(:posts => [{:comments => :guest}, :tags]) +This produces: + + +SELECT categories.* FROM categories + INNER JOIN posts ON posts.category_id = categories.id + INNER JOIN comments ON comments.post_id = posts.id + INNER JOIN guests ON guests.comment_id = comments.id + INNER JOIN tags ON tags.post_id = posts.id + + h4. Specifying Conditions on the Joined Tables You can specify conditions on the joined tables using the regular "Array":#array-conditions and "String":#pure-string-conditions conditions. "Hash conditions":#hash-conditions provides a special syntax for specifying conditions for the joined tables: -- cgit v1.2.3