Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between :model and @model in form_for?

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?

like image 372
Ryan Avatar asked Jan 13 '10 19:01

Ryan


2 Answers

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.

like image 164
Pär Wieslander Avatar answered Nov 07 '22 07:11

Pär Wieslander


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 %>
like image 26
Tomas Markauskas Avatar answered Nov 07 '22 06:11

Tomas Markauskas