diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 564aca8..bb86d23 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -1,5 +1,7 @@ == master +* Fix default headers including all model columns when using :select in the collection query + == 0.2.0 / 2009-04-25 * Reorganize documentation diff --git a/lib/table_helper/header.rb b/lib/table_helper/header.rb index 91b8571..e93da18 100644 --- a/lib/table_helper/header.rb +++ b/lib/table_helper/header.rb @@ -33,7 +33,17 @@ def initialize(table) # pre-fill the header with those columns so that the user doesn't # have to klass = table.klass - column(*klass.column_names.map(&:to_sym)) if klass && klass.respond_to?(:column_names) + if klass && klass.respond_to?(:column_names) + if !table.empty? && klass < ActiveRecord::Base + # Make sure only the attributes that have been loaded are used + column_names = table.collection.first.attributes.keys + else + # Assume all attributes are loaded + column_names = klass.column_names + end + + column(*column_names.map(&:to_sym)) + end @customized = false end diff --git a/test/app_root/app/models/person.rb b/test/app_root/app/models/person.rb new file mode 100644 index 0000000..2f2e286 --- /dev/null +++ b/test/app_root/app/models/person.rb @@ -0,0 +1,2 @@ +class Person < ActiveRecord::Base +end diff --git a/test/app_root/db/migrate/001_create_people.rb b/test/app_root/db/migrate/001_create_people.rb new file mode 100644 index 0000000..fbcf50c --- /dev/null +++ b/test/app_root/db/migrate/001_create_people.rb @@ -0,0 +1,11 @@ +class CreatePeople < ActiveRecord::Migration + def self.up + create_table :people do |t| + t.string :first_name, :last_name + end + end + + def self.down + drop_table :people + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index aadad93..eb11378 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -3,6 +3,9 @@ require 'rubygems' require 'plugin_test_helper' +# Run the migrations +ActiveRecord::Migrator.migrate("#{Rails.root}/db/migrate") + Test::Unit::TestCase.class_eval do private def assert_html_equal(expected, actual) diff --git a/test/unit/header_test.rb b/test/unit/header_test.rb index 6844539..5968b6c 100644 --- a/test/unit/header_test.rb +++ b/test/unit/header_test.rb @@ -250,3 +250,21 @@ def test_should_include_html_options_for_header_row assert_html_equal expected, @header.html end end + +class HeaderWithModelsTest < ActiveRecord::TestCase + def setup + Person.create(:first_name => 'John', :last_name => 'Smith') + end + + def test_should_include_all_columns_if_not_selecting_columns + table = TableHelper::CollectionTable.new(Person.all) + @header = TableHelper::Header.new(table) + assert_equal %w(first_name id last_name), @header.column_names.sort + end + + def test_should_only_include_selected_columns_if_specified_in_query + table = TableHelper::CollectionTable.new(Person.all(:select => 'first_name')) + @header = TableHelper::Header.new(table) + assert_equal %w(first_name), @header.column_names.sort + end +end