Difference between: model and @model in form_for?

What is the difference between using form_for as follows:

<% 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 @user only use automatic CRUD methods for URL actions?

+6
ruby-on-rails
source share
2 answers

If you give form_for character without an instance variable, it looks for an instance variable with the same name.

The documentation says:

For example, if @post is an existing post you want to edit

 <% form_for @post do |f| %> ... <% end %> 

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 %> 
+4
source share

If you just give a model example, for example @user , without specifying an action (as in the first example), Rails will automatically use 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 your edit and new views without changing the parameter :url for your forms.

As usual, the API docs provide additional information.

+7
source share

All Articles