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

后端 未结 4 757
时光取名叫无心
时光取名叫无心 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:20

    Thank you so much for your help as I said in my post the only problem with the approach from "Zaid Crouch"(I don't know how to make a reference to a user hehe) is that if the form has error fields the form will be clear and boom after the page reloading you'll have nothing filled in your form and can you imagine if you form is like 20 or 30 fields that would be a terrible user experience of course

    Here is my solution that works with validation models:

    class Registration < ActiveRecord::Base
      attr_accessible :foo, :bar, :registration_notes_attributes
      has_many :registration_notes
      has_one :new_registration, class_name: 'RegistrationNote'
      accepts_nested_attributes_for :new_registration
    end
    
    class RegistrationsController < ApplicationController
      def edit
       @registration = Registration.find(params[:id])
       @registration.build_new_registration
      end
    end
    
    <%= form_for @registration do |r| %>
      <%= r.text_field :foo %>
      <%= r.text_field :bar %>
      <%= r.fields_for :new_registration do |n| %>
        <%= n.text_area :content %>
      <% end %>
    <% end %>
    

    I'm using simple_form in my example if you want to see the same working with validations and transaction take a look at the complete post here: http://elh.mx/ruby/using-simple_form-for-nested-attributes-models-in-a-has_many-relation-for-only-new-records/

提交回复
热议问题