diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index 99a022461e..f3bb70fb41 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -30,6 +30,10 @@ module ActiveRecord attributes.select { |a| a.has_index? || (a.reference? && options[:indexes]) } end + def accessible_attributes + attributes.reject(&:reference?) + end + hook_for :test_framework protected diff --git a/activerecord/lib/rails/generators/active_record/model/templates/model.rb b/activerecord/lib/rails/generators/active_record/model/templates/model.rb index 5c47f8b241..d56f9f57a4 100644 --- a/activerecord/lib/rails/generators/active_record/model/templates/model.rb +++ b/activerecord/lib/rails/generators/active_record/model/templates/model.rb @@ -3,5 +3,10 @@ class <%= class_name %> < <%= parent_class_name.classify %> <% attributes.select {|attr| attr.reference? }.each do |attribute| -%> belongs_to :<%= attribute.name %> <% end -%> +<% if !accessible_attributes.empty? -%> + attr_accessible <%= accessible_attributes.map {|a| ":#{a.name}" }.sort.join(', ') %> +<% else -%> + # attr_accessible :title, :body +<% end -%> end <% end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb index acf47a03e5..03242a3bef 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -54,7 +54,7 @@ module <%= app_const_base %> # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. - # config.active_record.whitelist_attributes = true + config.active_record.whitelist_attributes = true # Specifies wether or not has_many or has_one association option :dependent => :restrict raises # an exception. If set to true, then an ActiveRecord::DeleteRestrictionError exception would be diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index 156fa86eee..e8d933935d 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -317,4 +317,14 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end end + + def test_attr_accessible_added_with_non_reference_attributes + run_generator + assert_file 'app/models/account.rb', /attr_accessible :age, :name/ + end + + def test_attr_accessible_added_with_comments_when_no_attributes_present + run_generator ["Account"] + assert_file 'app/models/account.rb', /# attr_accessible :title, :body/ + end end