Best practice for drying new and editable forms using partial

It should be easy, I'm noob.

I have new and editable representations for a model that use partial form rendering. For the edit form, I want to display a field that I do not want to display in the new form.

Should I pass in a local variable, pointing it to partial in editing mode and use the condition in partial display of the field?

What is the best practice in this case to partially find out what action is called?

+4
source share
3 answers

If you use form_for , you can use the same template for new and edit .

form_for will check if an object is being saved. If this is a new entry, the action url will point to #update , if it persists, it will point to #create .

So yes, your comment will work when using the same template for β€œnew” and β€œediting”. When is obj.new_record? , this is an editing form.

+2
source

This will only display the new form field

 <%# app/views/something/_form.html.erb %> <% form_for something do |form| %> <%# common fields ... %> <% if something.new_record? %> <%= form.text_field :foo %> <% end %> <% end %> 

If you want it in the edit form, just switch if to to unless

+6
source

If possible, try to avoid the conventions in your view (not always possible)

_form.html.erb

 # common fields only # ... 

_new.html.erb

 <%= form_for @your_model do |f| %> <fieldset> <% # render _form partial %> </fieldset> <div> <%= f.submit "Create New XXXX" %> </div> <% end %> 

_edit.html.erb

 <%= form_for @your_model do |f| %> <fieldset> <% # render _form partial %> <% # render fields that only appear for edit %> </fieldset> <div> <%= f.submit "Save Changes" %> <%= link_to 'Cancel', xxxx_path %> </div> <% end %> 
+1
source

Source: https://habr.com/ru/post/1488915/


All Articles