Skip to main content

Have filed entry populate fields in two tables - Nested Forms?

Rails • Asked by Simon Cooper

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


Hey Simon,

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

views/gins/_form.html.erb

<%= 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

models/gins.rb

class Gin < ApplicationRecord
  belongs_to :distillery

models/distilleries/distillery.rb

class Distillery < ApplicationRecord
  has_many :gins
  accepts_nested_attributes_for :gins

controllers/gin_controlller.rb

    def gin_params
      params.require(:gin).permit(:name, :text, :pic, :slug, distillery_attributes: [:id, :name])
    end

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.