Better way to retain form data on manual back redirect?
I have a form that, on submit, requires the customer to look over the data, and then confirm the changes before saving the data.
However, I'm using a really rough way of retaining data if the user hits the back button to go back and look over the data before submitting. Since I want the user's updates to the fields and not the current database fields, to be what displays on this "go back" action, I have to pass the values aroun开发者_如何学JAVAd via post/get params. So my controller looks something like:
@customer = Customer.find session[:id]
unless params[:customer].nil?
@customer.attributes = params[:customer]
end
Is there a better way to do this? I'm actually really curious what the generally accepted Rails session usage is as I'm pretty sure using the session for passing info like this is taboo. Yes, no? Thoughts? Thanks.
There may be a better way to do it involving sessions. I would rather avoid using the session hash entirely, with a second form and a lot of javascript.
Here's how I'd handle it. The first form wouldn't change much at all, just submit to a new action called review.
The review action will display the changes for review, and have an edit link and a confirm button visible. It will also recreate the form from the previous page in a hidden element which will submit again to the review action.
The confirm button would submit to your update action.
Clicking the edit link will hide the review area and show duplicated from from the previous page.
Here's some sample code to hammer down the point:
app/controllers/example_controller.rb
class ExampleController < ApplicationController
def edit
@example = Example.find(params[:id])
end
def review
@example = Example.find(params[:id])
@example.update_attributes(params[:example])
@example.valid?
end
def update
@example = Example.find(params[:id])
@example.update_attributes(params[:example])
if @example.save
redirect_to @example
else
render :action => :review
end
end
end
app/views/examples/_form.html.erb:
<% form_form @example, :url => {:action => "review"} do |f|%>
...
Form inputs go here
...
<% end %>
app/views/examples/edit.html.erb:
<%= render :parital => form %>
app/views/examples/review.html.erb:
<div id="review">
...
content for review goes here
...
<%= link_to_function "Edit", "$('review').hide(); $('edit').show()"
<% form_for @example do |f| %>
<%= hidden_field :attribute, @example.attribute %>
...
hidden_field for each attribute
...
<%= submit_tag "Accept These Changes" %>
<% end %>
</div>
<div id="edit" style="display:none">
<%= render :partial => 'form' %>
</div>
精彩评论