Have filed entry populate fields in two tables - Nested Forms?
I have two models, Gins and Distillery. At the moment, these are two completely seperate models, but I have been thinking that as a user adds a a new Gin and inputs it's distillery, this could also create a new entry in the Distillary table. Obviously Gin would then
belong_to distillery and Distillery would
has_many Gins. Looking around it seems a nested form could be the solution, but would that actually add the distillery value into both forms/tables. I haven't actually been able to get this to work, as the Distillary field in thh Gins form, wouldn't render
From first glance it looks like you may want to use something like Cocoon if you haven't tried that?
If you have code samples it may help more. I tend to have an easier time reasoning about things when there's code in front of me and it's not as abstract.
Absolutely Andrew. Here's what I have. An update from the above, is that I now have the 'distillery' field showing in the new form, but when I submit the form, i get the error:
Distillery must exist
<%= form_for(@gin, local: true, multipart: true) do |form| %> //some fields removed <div class="input-field"> <%= form.fields_for :distillery do |distillery_form| %> <p> <%= distillery_form.label :distillery %> <%= distillery_form.text_field :name %> </p> <% end %> </div> //some fields removed
class Gin < ApplicationRecord belongs_to :distillery
class Distillery < ApplicationRecord has_many :gins accepts_nested_attributes_for :gins
def gin_params params.require(:gin).permit(:name, :text, :pic, :slug, distillery_attributes: [:id, :name]) end