Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form_for and form_tag, when to use which one?

I am reading a Rails book and so far it has been using form_for to create the forms. In the new chapter that it is building a login page for users, it is using form_tag instead. So I wanted to know when and how we should know which one to use? Is it just a educational thing he has done to also show this form_tag too ? or there are more technical reasons that should be considered?

like image 406
Bohn Avatar asked Jan 22 '13 17:01

Bohn


People also ask

When would you use form_for and when would you use form_tag?

form_tag simply creates a form. form_for creates a form for a model object. They are not interchangeable and you should use the one that is appropriate for a given case.

What is the difference between Form_with and form_for?

You use form_for with a model and form_tag for custom URLs. Both generate HTML for a form . There are only a few minor differences so Rails 5.1 combined the two. You should now be using form_with .


1 Answers

form_tag simply creates a form. form_for creates a form for a model object. They are not interchangeable and you should use the one that is appropriate for a given case.

form_for is a bit easier to use for creating forms for a model object because it figures out what url to use and what http method to use depending on whether the object is a new record or a saved record.

like image 150
Shadwell Avatar answered Sep 28 '22 11:09

Shadwell