Reputation:
I have the following code but I am not able to understand hows does routing happen for form_for([@article, @article.comments.build]).
Title: <%= @article.title %>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
| <%= link_to 'Edit', edit_article_path(@article) %>
Upvotes: 5
Views: 1060
Reputation: 1162
To do that you would have to have your comments routs nested under your article. So your rout file would have something like this
resources :article
resources :comments
end
This creates several routes, the one this form would go it is
POST /posts/:post_id/comments
And in the form_for helper form_for([@article, @article.comments.build])
tells the form to post to that rout
Upvotes: 2
Reputation: 2121
Rails can imply the route from the form_for
e.g.
<%= form_for(@article) do |f| %>
...
<% end %>
If @article is new and not in the database, then rails can deduce you are creating a new one, then the route would be
articles_path(@article), action: :create
If @article already exists in the database then rails can deduce you are editing an existing object, so the path is.
article_path(@article), action: :update
This applies to nested routes as well like the example code you have.
<%= form_for([@article, @article.comments.build]) do |f| %>
It know the parent route is article and the sub route is comments, since it is a new comment, the route would be
article_comments_path(@article, @article.comments.build), action: :create
If comment exists then it will be an update action
article_comment_path(@article, @comment), action: :update
Any form_for, link_to, etc can imply the path from the objects.
Upvotes: 3