Skip to content

Loading…

Update to Arel::Table.alias method #5

Open
wants to merge 2 commits into from

1 participant

@ozzyaaron

Hi,

A colleague and I were using the Table.alias method today to do multiple joins on the same table but it wasn't working how we expected out of the box according to the readme page.

I've just updated the method to auto-increment the alias name if none is provided, otherwise the user can specify the name of the alias as they did previously.

I hope this is worthwhile :)

Thanks
Aaron

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Mar 31, 2011
  1. Added automatic incrementing of table alias names

    ozzyaaron committed
Showing with 39 additions and 1 deletion.
  1. +11 −0 README.markdown
  2. +1 −1 lib/arel/table.rb
  3. +27 −0 test/test_table.rb
View
11 README.markdown
@@ -109,3 +109,14 @@ The `parent_id` column is a foreign key from the `comments` table to itself. Now
# => SELECT * FROM comments INNER JOIN comments AS comments_2 WHERE comments_2.parent_id = comments.id
This will return the first comment's reply's body.
+
+If you wish to perform multiple joins to the same table then sometimes you may wish to specifically name the alias, the alias method takes
+a name parameter :
+
+ replies = comments.alias("r")
+ r.name # => 'r' is now used in the SQL query as the alias for comments.
+
+Usually though the alias name will be automatically created based on the number of aliases the table has.
+
+ replies = comments.alias # => replies.name == comments_2
+ more_replies = comments.alias # => more_replies.name == comments_3
View
2 lib/arel/table.rb
@@ -42,7 +42,7 @@ def primary_key
end
end
- def alias name = "#{self.name}_2"
+ def alias name = "#{self.name}_#{@aliases.length + 2}"
Nodes::TableAlias.new(name, self).tap do |node|
@aliases << node
end
View
27 test/test_table.rb
@@ -101,6 +101,33 @@ module Arel
node.name.must_equal 'users_2'
node[:id].relation.must_equal node
end
+
+ describe 'when given a alias name' do
+ it 'will give the alias the provided name' do
+ @relation.aliases.must_equal []
+
+ node = @relation.alias("test_alias")
+ @relation.aliases.must_equal [node]
+ node.name.must_equal 'test_alias'
+ node[:id].relation.must_equal node
+ end
+ end
+
+ describe 'when not given an alias name' do
+ it 'should increment alias names' do
+ @relation.aliases.must_equal []
+
+ node = @relation.alias
+ @relation.aliases.must_equal [node]
+ node.name.must_equal 'users_2'
+ node[:id].relation.must_equal node
+
+ node_2 = @relation.alias
+ @relation.aliases.must_equal [node, node_2]
+ node_2.name.must_equal 'users_3'
+ node_2[:id].relation.must_equal node_2
+ end
+ end
end
describe 'new' do
Something went wrong with that request. Please try again.