简体   繁体   中英

problem with RESTful forms in Rails 3

okay, so basically, I have a normal form for my model:

= form_for @operator do |f|
blah blah blah

In my operators controller, i have this:

def new
  @operator = Operator.new
  @operator.build_user

  respond_to do |format|
    format.html {}
  end
end

def create
  @user = User.create(params[:operator].delete(:user))
  @user.update_attributes(:login => @user.email)
  @operator = Operator.new(params[:operator].merge(:user => @user))

  respond_to do |format|
    if @operator.save
      format.html {redirect_to new_operator_aircraft_path(@operator)}
    else
      format.html { render :action => "new", :error => @operator.errors }
    end
  end
end

very basic stuff. I have some validates_presence_of stuff in my model so naturally when I submit my form, it should show me that I have errors(and keep the fields I have filled up)

Right so far? yeah. The problem is, it seems I am posting to /operators and that's what renders. I seem to have forgotten about what happens in Rails2.3+ but shouldn't I be redirected to /operators/new again? or was that the intended behavior all along?

Here's what I think you are asking:

After I submit a form with errors, why does the URL read "/operators" rather than "/operators/new".

Thanks to resourceful routing, when submitting a form via POST to "/operators" the create action is called on the OperatorsController. If you encounter errors when saving your operator, you've instructed the controller to render the new action within the same request.

render :action => "new", :error => @operator.errors

This means a redirect is not occurring and therefore the URL remains "/operators".

If a redirect were to occur, you would lose all the state information of the @operator object in the current request, including the errors you encountered as well as the form values you just submitted.

In other words, working as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM