Skip to content
This repository
Browse code

Whitelist all attribute assignment by default.

Change the default for newly generated applications to whitelist all attribute assignment.  Also update the generated model classes so users are reminded of the importance of attr_accessible.
  • Loading branch information...
commit 641a4f62405cc2765424320932902ed8076b5d38 1 parent c8f6025
Michael Koziarski authored March 05, 2012
4  activerecord/lib/rails/generators/active_record/model/model_generator.rb
@@ -30,6 +30,10 @@ def attributes_with_index
30 30
         attributes.select { |a| a.has_index? || (a.reference? && options[:indexes]) }
31 31
       end
32 32
 
  33
+      def accessible_attributes
  34
+        attributes.reject(&:reference?)
  35
+      end
  36
+
33 37
       hook_for :test_framework
34 38
 
35 39
       protected
5  activerecord/lib/rails/generators/active_record/model/templates/model.rb
@@ -3,5 +3,10 @@ class <%= class_name %> < <%= parent_class_name.classify %>
3 3
 <% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
4 4
   belongs_to :<%= attribute.name %>
5 5
 <% end -%>
  6
+<% if !accessible_attributes.empty? -%>
  7
+  attr_accessible <%= accessible_attributes.map {|a| ":#{a.name}" }.sort.join(', ') %>
  8
+<% else -%>
  9
+  # attr_accessible :title, :body
  10
+<% end -%>
6 11
 end
7 12
 <% end -%>
2  railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -54,7 +54,7 @@ class Application < Rails::Application
54 54
     # This will create an empty whitelist of attributes available for mass-assignment for all models
55 55
     # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
56 56
     # parameters by using an attr_accessible or attr_protected declaration.
57  
-    # config.active_record.whitelist_attributes = true
  57
+    config.active_record.whitelist_attributes = true
58 58
 
59 59
     # Specifies wether or not has_many or has_one association option :dependent => :restrict raises
60 60
     # an exception. If set to true, then an ActiveRecord::DeleteRestrictionError exception would be
10  railties/test/generators/model_generator_test.rb
@@ -317,4 +317,14 @@ def test_index_is_skipped_for_references_association
317 317
       end
318 318
     end
319 319
   end
  320
+
  321
+  def test_attr_accessible_added_with_non_reference_attributes
  322
+    run_generator
  323
+    assert_file 'app/models/account.rb', /attr_accessible :age, :name/
  324
+  end
  325
+
  326
+  def test_attr_accessible_added_with_comments_when_no_attributes_present
  327
+    run_generator ["Account"]
  328
+    assert_file 'app/models/account.rb', /# attr_accessible :title, :body/
  329
+  end
320 330
 end

0 notes on commit 641a4f6

Please sign in to comment.
Something went wrong with that request. Please try again.