Supersonic
Supersonic

Reputation: 430

Save as new record in edit action

Views: _form.html.erb

<%= form_for(@product) do |f| %>
   <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br />
    <%= f.number_field :price %>
  </div>
  <div class="actions">
    <%= f.submit "Save" %>
    <% if params[:action] == "edit" %>
      <% f.submit "Save As New" %>
    <% end %> 
  </div>
<% end %>

edit.html.erb

<%= render 'form' %>

In my products controller I have all the new,create,edit & update actions normally defined.

Question: This form update is working fine but I have a new submit button called "Save As New" is it anyway possible to invoke a create action inside the edit products page, when a user clicks on that.

I know the possibility to use a condition and check if params[:commit]=="Save As New" and try to invoke another action but I am not really sure if I can do that. How should I update my controller to make it work.

Thanks a ton.

Upvotes: 1

Views: 369

Answers (2)

davidb
davidb

Reputation: 8954

You can change the update action like this:

if params[:commit]=="Save As New"
  @product = Product.create(params[:product])
else
  @product.update_attributes(params[:product])
end
redirect_to @product

So you wont need a new action and can handle it without adding routes...

Upvotes: 3

dax
dax

Reputation: 10997

If I'm understanding it correctly, you want the user to be able to create a new record from inside in the edit page, right?

If that's the case, I think you can do this:

<div class="actions">
    <%= f.submit "Save" %>
    <% if params[:action] == "edit" %>
      <%= link_to "Save As New", {controller: 'products', 
                  action: 'new'
                  },
                  class: "if there's a css class"} %>

    <% end %> 
</div>

Upvotes: 2

Related Questions