Ruby on Rails: Create confirmation view before cre

2020-04-01 01:53发布

问题:

I have the below code for creating a product:

def create
    @customer = Customer.find(params[:customer_id])
    @product = @customer.products.build(params[:product])

    respond_to do |format|
      if @product.save
        format.html { redirect_to customer_products_path(@customer), notice: 'Product was successfully created.' }
      else
        format.html { render action: "new" }
        format.json { render json: customer_products_path.errors, status: :unprocessable_entity }
      end
    end
  end

To generate the form I use:

<%= form_for([@customer, @product]) do |f| %>

Now, I am wondering, how can I transfer the use to a separate confirmation page before saving the data to the DB. Also with an edit link, so if needed the user can make changes and submit the records finally.

I looked at other questions on stackoverflow, but was unable to create what I want. Any guidance is appreciated.

回答1:

If you want to do client-side confirmation, you need to use JavaScript to listen on the 'form submit' event. You then use jQuery html() to show a lightbox that asks to proceed or not. It would be related to using onsubmit event and rendering a confirmation box. Another way with data attributes is discussed here

If you want a database tracking for confirmation (server-side), you can render your model in the 'show' action, but with a different set of buttons.

In your show view, you would then do:

<% if @product.confirmed? %>
    ... # normal path to actions for show (edit, delete, back )
<% else %>
    <%= link_to "Confirm', confirm_product_customer_path(@product, @customer) %>
<% end %>

However, having an attribute for confirmation in the database, sometimes is a bit of overkill. As Jani suggests in the comments, a client-side confirmation is for most cases good enough.



回答2:

You can use a new button with a parameter:

  <%= f.submit %>
  <%= f.submit "Preview", :name => 'preview' %>

and in your controller, in create action:

if params[:preview]
@product = Product.new(params[:product])
render 'products/previw'
else
# save your object
end

and create a new partial for preview.