Reputation: 2523
In my routes.rb
I have the line resources :items
. I have a new.html.erb
file that is using form_for @item do ...
to build a form. In my items controller I define the new action:
def new
@item = Item.new
end
I am wondering what is the point of this new action definition. When the form is submitted I have a create action that handles it. Is it only for using form_for? What happens if I leave it out? Is there any rails magic going on that will assume this is what I want?
Upvotes: 0
Views: 292
Reputation: 293
By default, the new action will handle only GET requests. The create action will handle only POST requests. You can take a look of how Rails respond to specific request methods, using the rake routes
command.
The new action will respond to the browser's GET html request and assign a empty object, because the user didn't input anything yet. No validation error will be shown.
The create action expects the user has already submitted the form, and will trigger validations/etc. Then, if something wrong happened, it will re-render the form with validation errors. Otherwise, by default a redirect_to
will be triggered.
This is just the default. Rails is a Opinionated Framework, but very very flexible.
Upvotes: 1
Reputation: 36860
The new
creates a new object for the form_for. The form_for will know to submit create
(instead of update
) because the object is not persisted. And 'form_for' needs an object anyway (as do all model-backed forms).
new
also gives you an opportunity to set up initial values for some attributes, if you so desire.
So, all in all, it is helpful.
Upvotes: 1