Newbie Q: Why does scaffolding create new on 'new'?

Hi,

Apologies for what is a very basic question, but hopefully someone can
help me understand why the following is done in the Rails scaffolding:

Scaffolding creates, amongst others, these two methods in a controller:
‘new’ renders the ‘make new x record’ page. And ‘create’ deals with the
data sent back from the form on that page.

My question is - why does ‘new’ bother to create a new model object at
all? It’s not used in the rhtml template, and a new model object is
created as another new instance in ‘create’ anyway.

Scaffold methods for reference:

def new
@paper = Paper.new
end

def create
@paper = Paper.new(params[:paper])
if @paper.save
flash[:notice] = ‘Paper was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

Thanks for your insight, apologies again for what I’m assuming is a dumb
question…

  • N

I’m not sure about this (a really new RoR user), but I’d say RoR uses
the @paper instance on the View as a container of the inserted form
values, thus resending the new information back to the controller
(after a Submit action) encapsulated on the object (chech the params[]
hash to see how it travels).

But I could be wrong, since I’m recently learning this incredible and
interesting new framework :stuck_out_tongue:

On Oct 6, 6:38 pm, Peter L. [email protected]

Hi Peter

Forget about Rails Scaffolding and invest your time to look at Active
Scaffold :slight_smile:

CCH

On Oct 7, 7:38 am, Peter L. [email protected]

Peter L. wrote:

My question is - why does ‘new’ bother to create a new model object at
all? It’s not used in the rhtml template, and a new model object is
created as another new instance in ‘create’ anyway.

Scaffold methods for reference:

def new
@paper = Paper.new
end

Yeah its because the reference is used in the new.rhtml (well actually
the _form.rhtml to be precise)

The standard generated form uses methods of the object (in this case
Paper) to create the text fields and any error messages that may have
occured.

i.e. in _form.rhtml

<-- error_messages expects a ActiveRecord Object @paper to test for errors --> <%= error_messages_for 'paper' %>

Name

<-- text_field expects @paper and will use @paper.name fill in the value
–>
<%= text_field ‘paper’, ‘name’ %>

Hope that makes sense

Luke

Hope that makes sense

It does! Those partials can be sneaky! Thanks for your time.

I dont think this is good advice. I definitely recommend that newbies
experiment with the built in scaffolding, to learn the rails
conventions and fundamentals. Then, move on, remembering Rails
scaffolding, you will probably write your own controllers. Or perhaps
pick up a plug in like Active Scaffold (which do I use and like alot,
btw) if you want ajaxy tables in your views.