user3277633
user3277633

Reputation: 1923

rails form_for with associated models

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..?

Upvotes: 2

Views: 415

Answers (1)

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

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.

Upvotes: 4

Related Questions