Skip to content
This repository has been archived by the owner on Aug 17, 2017. It is now read-only.

Ensure that the key in require is valid. #148

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

bryanrite
Copy link
Contributor

A proof of concept of ensuring that the key returned from require is valid. Can use from refactoring if this is a feature we want to accept.

This is to get around a NoMethod exception raised by valid JSON, but invalid input as explained in issue #140

@arthurnn
Copy link
Member

👍 for this, or a new method, which would force the hash type. right now it is really common to follow the pattern:

def person_params
  params.require(:person).permit(:name, :age)
end

and if someone send a string on the person parameter, that would cause a 500 and not a 400.

@airhorns
Copy link

👍

@bds
Copy link

bds commented Mar 28, 2014

I think I am running into a similar issue.

it "should return 400 (Bad Request) when the job_template is missing an :id attribute" do
  post(api_v1_jobs_path, {:job_template => "5ceb8bb8235bcc76bf475e21"}, @env)
  response.status.should eql(400)                                           
end
# => returns 500
def create                                                                
  params.require(:job_template).permit(:id)                               
  render json: {}                                                         
end

Would a better way to handle this be?

# code not tested
def create                                                                
  params.require(:job_template)
  @job_template = JobTemplate.new(params[:job_template])
  render :status => 400 and return unless @job_template.valid?
end

I have not tried this yet since I have not yet created a JobTemplate model

@bryanrite
Copy link
Contributor Author

Ping? Can I help move this along in any way?

Since valid JSON sent to a controller but not in the right "format" that strong params expects should return a 4xx... not a 500. My current solution to this (as I stated in #140) is:

rescue_from NoMethodError do |exception|
  if exception.message =~ /undefined method `permit' for/
    render json: { message: "Helpful error message..." }, status: :bad_request
  else
    raise
  end
end

Not ideal but functional.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants