I 'm using Rails 5. I have a page where a user can update their profile and if something goes wrong, they are returned to the page
def update
@user = current_user
if @user.update_attributes(user_params)
…
redirect_to url_for(:controller => ‘main’, :action => 'index') and return
end
render 'edit'
end
The problem is, when they are returned to the original page, the URL in the browser bar reads, “http://localhost:3000/users/51”, which is not the original URL they were visiting (that was “http://localhost:3000/users/edit”). How can I get the URL to remain the same as what it was?
Edit: This is what is produced when I run rake routes
edit_users GET /users/edit(.:format) users#edit
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
and return
is a bad habit to get into as there's no guarantee that things like theredirect_to
method returns a logically true value. It's much better to doreturn redirect_to ...
so there's no chance that will fail. – Haynie@user.update_attributes!
and redirecting. If there's a problem updating you'll get anActiveRecord::RecordInvalid
error which you can rescue and handle withrender(action: 'edit')
. – Haynieedit
action, so of course it won't be the same. The only way to fix that is with some URL trickery, like HTML5 history manipulation, or by doing the validation remotely using AJAX before submitting to be sure it's already good to go before you commit and redirect. That's usually a lot more work. – Haynie