What is the difference between using form_for the following way:
<% form_for @user do |f| %>
<%= f.label :name %>:
<%= f.text_field :name, :size => 40 %>
...
<% end %>
and:
<% form_for :user, :url => {:action => 'create'} do |f| %>
<%= f.label :name %>:
<%= f.text_field :name, :size => 40 %>
...
<% end %>
Does using @user just automatically use CRUD methods for the URL actions?
If you just give a model instance like @user
without specifying an action (as in your first example), Rails automatically uses the appropriate CRUD action for your form:
If @user
is a new, unsaved User
object, the form will point to your create
action.
If @user
is an existing User
loaded from the database, the update
action will be used instead.
This has the advantage that you can reuse the same form for both your edit
and new
views without changing the :url
parameter for your forms.
As usual, the API docs provide more information.
If you give form_for
a symbol without an instance variable it looks for an instance variable with the same name.
The documentation says:
For example, if @post is an existing record you want to edit
<% form_for @post do |f| %> ... <% end %>
is equivalent to something like:
<% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %> ... <% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With