form_for

At the following: http://edgeguides.rubyonrails.org/getting_started.html

Under: 7.4 Generating a Controller

It mentions the following:

<%= form_for([@post, @post.comments.build]) do |f| %>

Now, this is what I know:

form_for: used to generate a form.
@post: the object form_for is bound to.

The part I didn't get here is:

@post.comments.build

What does that part provide me with?

Thanks.

At the following:http://edgeguides.rubyonrails.org/getting_started.html

Under: 7.4 Generating a Controller

It mentions the following:

<%= form_for([@post, @post.comments.build]) do |f| %>

Now, this is what I know:

form_for: used to generate a form.
@post: the object form_for is bound to.

The part I didn't get here is:

@post.comments.build

What does that part provide me with?

It's a namespaced resource - it's a form for a new comment belonging
to @post

Fred

Frederick Cheung wrote:

Have a look at the guide on routing, (at
http://edgeguides.rubyonrails.org/) it explains the use of namespaces.

Also google would have given you useful information here again.

Colin

Thanks Colin.

This is a method generated for you by rails as a result of the
associtions declared in the Post and Comment models - in this case
belongs_to and has_many. Comments belongs to a post, and a post can
have many comments.

Rails creates quite a number of theses methods in response to the
association, and different associations (has_one,
has_and_belongs_to_many etc.) create different sets of methods - more
details in the API docs: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

collection.build is one of these methods, and the API docs explain it
pretty well:

"collection.build(attributes = {}, …) Returns one or more new
objects of the collection type that have been instantiated with
attributes and linked to this object through a foreign key, but have
not yet been saved."

"collection" in this case is @post.comments

(None of of which has anything to do with namespaced resources...)

Matt.