Created
December 23, 2011 16:54
-
-
Save rogercampos/1514743 to your computer and use it in GitHub Desktop.
Redisplay a filled form with redirect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In the controller | |
def update | |
@model = Model.find params[:id] | |
if @model.update_attributes(params[:model]) | |
redirect_to an_url | |
else | |
save_for_redisplay(@model) | |
redirect_to other_url | |
end | |
end | |
# In the view | |
= form_for load_or_build_to_redisplay(:model) do | |
# Normal fields |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In some helper | |
def saved_for_redisplay?(obj) | |
obj_name = ActiveRecord::Base === obj ? obj.class.model_name.underscore : obj.to_s | |
flash.has_key?(:"saved_#{obj_name}_for_redisplay") | |
end | |
def load_or_build_to_redisplay(model_name) | |
if saved_for_redisplay?(model_name) | |
obj = model_name.to_s.classify.constantize.new flash[:"saved_#{model_name}_for_redisplay"] | |
obj.valid? | |
obj | |
else | |
model_name.to_s.classify.constantize.new | |
end | |
end | |
# In the controller | |
def save_for_redisplay(obj) | |
flash[:"saved_#{obj.class.model_name.underscore}_for_redisplay"] = obj.attributes | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment