Skip to content

Commit

Permalink
Revert params.fetch to params.expect conversions in scaffold
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
martinemde authored and DanielaVelasquez committed Oct 3, 2024
1 parent e1e063c commit 9cca847
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class <%= controller_class_name %>Controller < ApplicationController
# Only allow a list of trusted parameters through.
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
params.expect(<%= singular_table_name %>: {})
params.fetch(:<%= singular_table_name %>, {})
<%- else -%>
params.expect(<%= singular_table_name %>: [ <%= permitted_params %> ])
<%- end -%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class <%= controller_class_name %>Controller < ApplicationController
# Only allow a list of trusted parameters through.
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
params.expect(<%= singular_table_name %>: {})
params.fetch(:<%= singular_table_name %>, {})
<%- else -%>
params.expect(<%= singular_table_name %>: [ <%= permitted_params %> ])
<%- end -%>
Expand Down
11 changes: 10 additions & 1 deletion railties/test/generators/scaffold_controller_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def test_dont_use_require_or_permit_if_there_are_no_attributes

assert_file "app/controllers/users_controller.rb" do |content|
assert_match(/def user_params/, content)
assert_match(/params\.expect\(user: \{\}\)/, content)
assert_match(/params\.fetch\(:user, \{\}\)/, content)
end
end

Expand Down Expand Up @@ -357,6 +357,15 @@ def test_api_only_generates_params_for_attachments
end
end

def test_api_only_doesnt_use_require_or_permit_if_there_are_no_attributes
run_generator ["User", "--api"]

assert_file "app/controllers/users_controller.rb" do |content|
assert_match(/def user_params/, content)
assert_match(/params\.fetch\(:user, \{\}\)/, content)
end
end

def test_check_class_collision
Object.const_set :UsersController, Class.new
content = capture(:stderr) { run_generator }
Expand Down

0 comments on commit 9cca847

Please sign in to comment.