Peter Nixey
Peter Nixey

Reputation: 16565

Is the "Rails Way" for `update` fundamentally flawed?

I'm intentionally asking this question in an inflammatory way because I'm concerned that I'm missing something.

The Rails Way for dealing with an update to a model is the following:

class UsersController < ApplicationController
  ...
  def update
    @current_user = load_user
    if @current_user.update_attributes params[:user]
      redirect_to success_path
    else
      render :edit
    end
  end
end

This is all well and good except that you end up on an odd URL when the form submission is incorrect:

Editing User

You find yourself on the path:

users/:user_id/edit

After submitting edits that don't validate

i.e. you're going to need to fix the inputs in your form and resubmit:

users/:user_id

After submitting edits that do validate

success_path

Why the hell should you be on a different URL just because the form has errors?


The problem...

You're doing the same thing but you're now on a different URL. This is a bit odd.

In fact frankly it feels wrong. You're on a form which has not validated correctly and so has reloaded. You should still be on /users/:user_id/edit. If you'd done JS validation you would be.

Furthermore if you've got any "currently selected" logic going on in your navigation then you are in fact visually in the wrong place as the correct nav item is no longer highlighted - it looks like you're on the user profile page.

Upvotes: 4

Views: 182

Answers (2)

Art Shayderov
Art Shayderov

Reputation: 5110

Actually it's not the "Rails Way", it's "REST Way". Wikipedia: Representational state transfer

If you follow the rules you get REST-compliant web-service for free. As I understand it the path "resource/id/edit" is specific to html documents. Web-service clients don't need form for editing.

So the guys were trying to be consistent. If you don't need web-service compatibility you can change the routes of course.

Upvotes: 0

Pavling
Pavling

Reputation: 3963

Why the hell should you be on a different URL just because the form has errors?

Because when you first went to:

users/:user_id/edit

...you were requesting a GET.

Then you POSTed to:

users/:user_id

So by sending the form post, you have requested a different resource route, and have a different URL by definition.

The framework doesn't care what happened in the background while your request was processing - all it knows is it was a POST (which by convention is not necessarily idempotent as a GET is)

Upvotes: 6

Related Questions