TradeRaider
TradeRaider

Reputation: 754

Why do we declare a @page = Page.new under new action, in Rails?

This question is about Rails 3.2 and a bit more complicated than the title suggests.

Say we have a Pages controller, with all the RESTful actions. This web app can create pages, display, edit and delete existing ones, and list all of the existing pages.

Under the new action, I have some code like

@page = Page.new

So, when the user visits /pages/new, and fill the form_for(@page) do..end stuff, will the input data get saved to @page? For instance, if title and content are the page model attributes, will @page.title and @page.content return an error or display what we are seeking for? Or will the form_for directly save the values onto params?

If later is the case, why do we declare @page in new action? Is it there so that form_for could infer that Rails is about to create a new Page model object rather than an existing one?

Hopefully, that wasn't too confusing. :P

Upvotes: 1

Views: 177

Answers (2)

Mike Szyndel
Mike Szyndel

Reputation: 10592

You can have a form for a class just by writing

form_for :post

In Rails it is a convention to make a form with

form_for @post

because then you can render the same form partial for new, create (on validation errors) edit, and update (on validation error) actions. That's why you need to initialize an new "empty" object in new action - to keep the interface uniform.

Upvotes: 3

SteveTurczyn
SteveTurczyn

Reputation: 36860

It's so that form_for displays ah empty page and the form_for ... because it has an empty object for reference ... can infer from the model how the form should be constructed.

This explains it in some detail...

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for

Instance variables like @page don't persist after the page is rendered so when the form data is returned you'll be using that form data to create a new page object in your controller logic.

Typically if you can't save the new object because of validation errors, you will re-render the form page with the unsaved object instance, so the field will show the data the user entered and the user can correct any problems.

Upvotes: 2

Related Questions