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

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Simon Cooper asked in Rails

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
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 35,699+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.