2

In the official rails guide, I came across

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

I am not quite sure what the two parameters of form_for are representing. I think the first parameter @article is referring to the associated model of comments and article, and the second parameter appears to be creating a new comment.

Why are they there and why are both parameters in an array..?

1 Answer 1

4

What is being demonstrated by this particular code snippet is nested routing.

Non-nested Routing

In a form_for call, the method argument is used to determine which resource URL the form should submit to. For example, if we have form_for(@article) then the form will submit to the routes for the "article" resource (either POST /articles or PUT/PATCH /articles/:id depending on if the record was new or existing).

Nested Routing

A nested route is one that has two levels of resources in the URL. For example, you might have a "comment" resource which is nested under an "article" resource (because comments belong to articles). In this case, the routes for a form_for would look like POST articles/:article_id/comments and PUT articles/:article_id/comments/:id.

Array as an argument

The array as an argument to the form_for call indicates that the resources will be nested, and therefore to submit the form to a nested route.

For deeply nested routes (not recommended) you could continue to add objects to the array for every level that you need, e.g. [@category, @article, @comment] which goes to /categories/:category_id/articles/:article_id/comments


In the particular case shown by the OP, it will submit to the POST "articles/#{@article.id}/comments" because @articles.comments.build is a new comment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.