Search code examples
ruby-on-railsformsmodel-view-controller

how does form_for know the difference when submitting :new :edit


I've generated a scaffold, let's call it scaffold test. Within that scaffold, I've got a _form.html.erb thats being render for action's :new => :create and :edit => :update

Rails does a lot of magic sometimes and I cannot figure out how the form_for knows how to call the proper :action when pressing submit between :new and :edit

Scaffolded Form

<%= form_for(@test) do |f| %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

vs. Un-scaffolded Form

 <% form_for @test :url => {:action => "new"}, :method => "post" do |f| %>
       <%= f.submit %>
 <% end %>

#Edit template

Editing test

<%= render 'form' %>

#New template

New test

<%= render 'form' %>

As you can see theres no difference between the forms How can both templates render the same form but use different actions?


Solution

  • It checks @test.persisted? If it is persisted then it is an edit form. If it isn't, it is a new form.