From 1d0e8f6a943be58f36eb2ec6f768ef3262fbc209 Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Mon, 15 Sep 2008 10:35:26 +0100 Subject: [PATCH] enable use of select with :include --- activerecord/lib/active_record/associations.rb | 14 ++++++++++++-- activerecord/test/cases/finder_test.rb | 4 ++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 5d91315..84970da 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1604,7 +1604,9 @@ module ActiveRecord def construct_finder_sql_with_included_associations(options, join_dependency) scope = scope(:find) - sql = "SELECT #{column_aliases(join_dependency)} FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " + select_options = options[:select] || (scope && scope[:select]) + + sql = "SELECT #{column_aliases(join_dependency)} #{select_options ? ", #{select_options}" : ''} FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " sql << join_dependency.join_associations.collect{|join| join.association_join }.join add_joins!(sql, options[:joins], scope) @@ -1785,6 +1787,11 @@ module ActiveRecord end def instantiate(rows) + unless rows.empty? + keys_from_select = rows.first.keys.reject {|k| k =~ /\At\d+_/} + join_base.extra_columns = keys_from_select + end + rows.each_with_index do |row, i| primary_id = join_base.record_id(row) unless @base_records_hash[primary_id] @@ -1918,6 +1925,7 @@ module ActiveRecord class JoinBase # :nodoc: attr_reader :active_record, :table_joins + attr_accessor :extra_columns delegate :table_name, :column_names, :primary_key, :reflections, :sanitize_sql, :to => :active_record def initialize(active_record, joins = nil) @@ -1951,7 +1959,9 @@ module ActiveRecord end def extract_record(row) - column_names_with_alias.inject({}){|record, (cn, an)| record[cn] = row[an]; record} + record = column_names_with_alias.inject({}){|record, (cn, an)| record[cn] = row[an]; record} + extra_columns.inject(record){|record, an| record[an] = row[an]; record} if extra_columns + record end def record_id(row) diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index cbdff38..983e8ad 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -993,9 +993,9 @@ class FinderTest < ActiveRecord::TestCase end def test_with_limiting_with_custom_select - posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id') + posts = Post.find(:all, :include => :author, :select => 'LOWER(authors.name) as "lower_name"', :limit => 3, :order => 'posts.id') assert_equal 3, posts.size - assert_equal [0, 1, 1], posts.map(&:author_id).sort + assert_equal 'david', posts.detect {|p| p.author_id == 1}.lower_name end protected -- 1.6.0.1