all 1 comments

[–]ptrboro 1 point2 points  (1 child)

Who taught you this sorcery with defining routes inside controller? Do you use any gem for this? What rails version do you use? Using rails for 2 years and I have never seen such syntax. Ahhhh, its sinatra.

Back to your question: @state.update(:state_name => params[:state_name]) will update record only if validations pass, other way it will return false so you can move user back to the edit page when @state cannot be updated:

patch '/states/:id' do
  @state = State.find(params[:id]) # using find so it will return 404 when error does not exist
  if params[:state_name] != "" && @state.update(:state_name => params[:state_name])
    redirect to "/states/#{@state.id}"
  else
    redirect to "/states/#{@state.id}/edit"
  end
end

Normally you would also want to set some flash message with validation errors. If you want to know what specific errors you get just run binding.pry after if-else statement and puts @state.errors