sbak
sbak

Reputation: 63

Model in form_with

I was reading the guide on the ruby on rails. I stuck at here: https://guides.rubyonrails.org/getting_started.html#generating-a-controller

I have doubt how they have used form_with(model: [ @article, @article.comments.build ], local: true)

In this what does the model attribute means and also what is the significance of build in @article.comments.build.

Can someone please explain me this.

Upvotes: 0

Views: 2252

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21110

The form_with model: ... and form_for ... both accept a resource-oriented style.

Your given example:

[@article, @article.comments.build]

Will be translated to (assuming article with id 1):

POST /articles/1/comments

Passing an array as recourse will assume a nested or namespaced resource. The last item in the array should be resource to work on. If this last item is a new record the form will use POST if it is an existing resource PUT will be used.

Here are a few examples to clarify things:

[@existing_article]
# PUT /articles/1

[@new_article]
# POST /articles

[@article, @existing_comment]
# PUT /articles/1/comments/1

[@article, @new_comment]
# POST /articles/1/comments

[:admin, @existing_article]
# PUT /admin/articles/1

[:admin, @new_article]
# POST /admin/articles

[@article, :admin, @existing_comment]
# PUT /articles/1/admin/comments/1

[@article, :admin, @new_comment]
# POST /articles/1/admin/comments

In your scenario @article.comments.build sets the subject of the form builder to a comment (because it is the last item in the array) and dictates the path/URL and method used when submitting the form.

Upvotes: 2

Related Questions