stephenmurdoch
stephenmurdoch

Reputation: 34643

Rails - confused by URL change when model validations fail

I've got a User resource where :name is a required attribute on the model.

If I try to create a new user without a name, then the validation fails and the error messages are displayed at the top of the form as expected, but the URL of the page changes from /users/new, to /users?

I hadn't noticed this behaviour until tonight when I started playing around with capybara for the first time, and was expecting the current_path after a validation failure to be http://localhost:3000/users/new

I couldn't figure out why my spec was failing:

it 'should not create an invalid user' do
  fill_in "Name", :with=>""
  click_button "Create User"
  current_path.should == new_users_path
end

I've verified that it happens in all my other rails apps, so I realise this is the way rails works, but I really don't get what's going on here. Why does it work like this? Why does the path change from new_users_path to users_path when validations fail?

This has confused me immensely

Upvotes: 5

Views: 1397

Answers (1)

apneadiving
apneadiving

Reputation: 115541

It's perfectly normal.

In a basic CRUD, you're creating your users using a POST request to /users.

If validation fails, you just render the edit view, but it doesn't change the url.

To change the url, you should redirect_to but, this way you'd loose the info related to the performed validation.

Upvotes: 3

Related Questions