I'm having trouble grasping this issue. I have a model (Invoice) that belongs_to
another model (Customer) and a customer has_many
invoices.
So an invoice cannot be created without a customer. I would like to be able to create a customer with the invoice at the same time with the same form.
Right now I just have it so you can manually punch in an invoice_id
and it all works fine but that isn't ideal for someone actually using the application for obvious reasons.
I've read up on this article but I still don't understand and was also unsure if this is still applicable with Rails 5: https://stackoverflow.com/a/3809360/7467341
Is the above answer still the correct approach? Could someone clarify and maybe give me some code to try? Thanks!
<%= form_for(invoice) do |f| %>
<% if invoice.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(invoice.errors.count, "error") %>
prohibited this invoice from being saved:</h2>
<ul>
<% invoice.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<h2>Customer Info</h2>
<hr>
<div class="field">
<%= f.label :customer_id %>
<%= f.number_field :customer_id %>
</div>
<!-- My customer model has more fields that I want to go here (name, address, and phone_number) -->
[...] other regular invoice fields here...
<div class="actions">
<%= f.submit %>
</div>
<% end %>