Skip to content

Commit

Permalink
prepend table name for Relation#select columns.
Browse files Browse the repository at this point in the history
This fixes a bug where `select(:id)` combined with `joins()` raised:

```
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: id:
SELECT  id, authors.author_address_id
FROM "posts"
INNER JOIN "authors"
ON "authors"."id" = "posts"."author_id"
ORDER BY posts.id LIMIT 3
```

The `select_values` are still String and Symbols because other parts (mainly calculations.rb)
rely on that fact.

/cc @tenderlove
  • Loading branch information
senny committed Jan 21, 2014
1 parent c60e062 commit e011258
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
10 changes: 10 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,13 @@
* Prepend table name for column names passed to `Relation#select`.

Example:

Post.select(:id)
# Before: => SELECT id FROM "posts"
# After: => SELECT "posts"."id" FROM "posts"

*Yves Senn*

* Fail early with "Primary key not included in the custom select clause"
in `find_in_batches`.

Expand Down
5 changes: 4 additions & 1 deletion activerecord/lib/active_record/relation/query_methods.rb
Expand Up @@ -987,7 +987,10 @@ def build_joins(manager, joins)

def build_select(arel, selects)
if !selects.empty?
arel.project(*selects)
expanded_select = selects.map do |field|
columns_hash.key?(field.to_s) ? arel_table[field] : field
end
arel.project(*expanded_select)
elsif from_value
arel.project(Arel.star)
else
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/relations_test.rb
Expand Up @@ -1505,6 +1505,12 @@ def test_presence
end
end

test "joins with select" do
posts = Post.joins(:author).select("id", "authors.author_address_id").order("posts.id").limit(3)
assert_equal [1, 2, 4], posts.map(&:id)
assert_equal [1, 1, 1], posts.map(&:author_address_id)
end

test "delegations do not leak to other classes" do
Topic.all.by_lifo
assert Topic.all.class.method_defined?(:by_lifo)
Expand Down

0 comments on commit e011258

Please sign in to comment.