Reputation: 14158
I want to have my Add and Edit forms for a model on the same page. You can see in this screenshot that I'm showing and hiding the 2 forms with JS:
In the edit form, the user selects an Aircraft ID and it populates the other data with some Ajax.
Currently, I'm rendering the two forms from partials like this:
<!-- Add Aircraft -->
<div id="aircraftmodal-add-content">
<%= render 'aircrafts/new' %>
</div>
<!-- Edit Aircraft -->
<div id="aircraftmodal-edit-content">
<%= render 'aircrafts/edit' %>
</div>
My forms render near-identical content, and I'm hacking around it by giving the Edit form a different ID:
<!-- Add Partial --->
<%= form_for @aircraft, validate: true, remote:true do |air| %>
<!-- Edit Partial -->
<%= form_for @aircraft, :html => { id:'edit_aircraft'}, validate: true, remote:true do |air| %>
Can I somehow use the built-in Rails goodness for handling edits when I'm putting 2 forms together on the same page like this? Will I have to point the Edit form to a different action, or can the usual code handle both?
def create
@aircraft = current_user.aircrafts.build(params[:aircraft])
@aircraft.save
end
I welcome your guidance. :)
Upvotes: 1
Views: 2092
Reputation: 1367
You can use @aircraft.persisted?
to know if the aircraft if a new register (new/create actions) or if it's already persisted (edit/update actions).
Using the same form, you dont need to specify the id, Rails already assigns diferent ids 'new_aircraft' and 'edit_aircraft_X', where X is the aircraft id.:
And to to change the select/input_text you can use:
<% if @aircraft.persisted? %>
<%= select... %>
<% else %>
<%= input... %>
<% end %>
Upvotes: 2
Reputation: 4496
If you about DRY, so what about using locals?
<div id="aircraftmodal-add-content">
<%= render 'aircrafts/form', :dom_id => "new_aircraft" %>
</div>
<!-- Edit Aircraft -->
<div id="aircraftmodal-edit-content">
<%= render 'aircrafts/form', :dom_id => "edit_aircraft" %>
</div>
<!-- Form Partial -->
<%= form_for @aircraft, :html => { id: dom_id }, validate: true, remote:true do |air| %>
<% if dom_id == "edit_aircraft" %>
<%= ... select aircraft id ... %>
<% elsif dom_id == "new_aircraft" %>
<%= ... input aircraft id ... %>
<% end %>
etc...
Upvotes: 4