How to get Rails build and fields_for to create only a new record and not include existing?

后端 未结 4 754
时光取名叫无心
时光取名叫无心 2020-12-13 04:41

I am using build, fields_for, and accepts_nested_attributes_for to create a new registration note on the same form as a new registrati

4条回答
  •  温柔的废话
    2020-12-13 05:23

    If you want to create a new registration form on your edit action, you can just instantiate a new registration_note object. Right now, your form is for the existing registration object.

    I believe this is what you want:

    class RegistrationsController < ApplicationController
      def edit
        @new_registration_note = RegistrationNote.new
        @registration = Registration.find(params[:id])
        @registration.registration_notes.build
      end
    end
    

    In your view, you should pass a hidden param that references the registration record id:

    <%= form_for @new_registration_note do |r| %>
      <%= r.hidden_field :registration_id, :value => @registration.id  %>
      <%= r.text_area :content  %>
    <% end %>
    

    Now, you can create your new registration note that belongs to @registration. Make sure you have a column in your registration_notes table to point to the registration. You can read more about associations here: http://guides.rubyonrails.org/association_basics.html

提交回复
热议问题