Instead of calling render
, you can redirect_to
the edit page, and use flash
to keep track of the model:
def update
# ...
if !@model.save # there was an error!
flash[:model] = @model
redirect_to :action => :edit
end
end
And then in the edit
action you can reload the values from flash[:model]
, ie:
def edit
if flash[:model]
@model = flash[:model]
else
@model = ... # load model normally
end
end
Update:
As commented below, I think when I wrote this answer I was trying to provide a way to both update the URL (which requires a redirection) and keep the changed attributes of the model, which is why the model was stored in flash. However, it's a pretty bad idea to stick a model into flash (and in later versions of Rails it'll just get deserialized anyways), and RESTful routes don't really require making the URL contain edit
.
The usual pattern would be to just render the edit action with the model already in memory, and forego having the "ideal" URL:
def update
# Assign attributes to the model from form params
if @model.save
redirect_to action: :index
else
render :edit
end
end
Alternately, if it's preferable to have the "ideal" URL and you don't care about maintaining changed attributes that failed validation, see @jamesmarkcook's answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…