Skip to content

Commit 1929503

Browse files
committed
Revert params.fetch to params.expect conversions in scaffold
The conversions have the unintended consequence of requiring params when none are expected. Ensure generated templates work as is. Adds a missing test for the api controller generation. Originally pointed out in rails/jbuilder#573.
1 parent 6e46b42 commit 1929503

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb.tt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ class <%= controller_class_name %>Controller < ApplicationController
4848
# Only allow a list of trusted parameters through.
4949
def <%= "#{singular_table_name}_params" %>
5050
<%- if attributes_names.empty? -%>
51-
params.expect(<%= singular_table_name %>: {})
51+
params.fetch(:<%= singular_table_name %>, {})
5252
<%- else -%>
5353
params.expect(<%= singular_table_name %>: [ <%= permitted_params %> ])
5454
<%- end -%>

railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb.tt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ class <%= controller_class_name %>Controller < ApplicationController
5555
# Only allow a list of trusted parameters through.
5656
def <%= "#{singular_table_name}_params" %>
5757
<%- if attributes_names.empty? -%>
58-
params.expect(<%= singular_table_name %>: {})
58+
params.fetch(:<%= singular_table_name %>, {})
5959
<%- else -%>
6060
params.expect(<%= singular_table_name %>: [ <%= permitted_params %> ])
6161
<%- end -%>

railties/test/generators/scaffold_controller_generator_test.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def test_dont_use_require_or_permit_if_there_are_no_attributes
6767

6868
assert_file "app/controllers/users_controller.rb" do |content|
6969
assert_match(/def user_params/, content)
70-
assert_match(/params\.expect\(user: \{\}\)/, content)
70+
assert_match(/params\.fetch\(:user, \{\}\)/, content)
7171
end
7272
end
7373

@@ -357,6 +357,15 @@ def test_api_only_generates_params_for_attachments
357357
end
358358
end
359359

360+
def test_api_only_doesnt_use_require_or_permit_if_there_are_no_attributes
361+
run_generator ["User", "--api"]
362+
363+
assert_file "app/controllers/users_controller.rb" do |content|
364+
assert_match(/def user_params/, content)
365+
assert_match(/params\.fetch\(:user, \{\}\)/, content)
366+
end
367+
end
368+
360369
def test_check_class_collision
361370
Object.const_set :UsersController, Class.new
362371
content = capture(:stderr) { run_generator }

0 commit comments

Comments
 (0)