If we create the default scaffold in Rails, both the edit.html.erb and new.html.erb render the same _form.html.erb within. Both create forms with certain similarities and differences.
Such as:
- Both create
<form method="post" ...> - The submit buttons have different texts
<input value='Create model'and
..<input value='New model' ..
My questions:
- How does the conditional rendering work?
- How to display form elements conditionally? E.g., show this
<input>only if it is called viaedit.html.erb, but do not show
it if called vianew.html.erb. - If the method in q.2 possible, is it the right way? We are reusing
code instead of replicating the form all over again, isn’t it?
Assuming you’re following RESTful conventions, the differences you see between edit and new are based on the state of the object that you pass to the form. Rails can tell the difference between a new object and one that has been persisted by using the
#new_record?method.In your
#newcontroller action, you probably have something like:In your
#editaction, you probably have something like:This
@modelobject is then passed to the form, which handles the conditional logic internally. Another difference in the form you should notice is that the#editversion has a hidden input field that tells the server to use thePUTHTTP method.Update
It looks like Rails actually uses the persisted? method internally as opposed to new_record?. The difference is that persisted? checks whether the record has been deleted. Otherwise, they are identical (but opposite)