Alternative for accepts_nested_attributes_for - maybe virtus

后端 未结 4 639
萌比男神i
萌比男神i 2021-02-07 04:21

I\'m relatively new to rails and finally found the right way to use accepts_nested_attributes_for.

However, there are some serious resources on the web who

4条回答
  •  暖寄归人
    2021-02-07 04:57

    So, the accepted answer just says why accepts_nested_attributes_for is often a good solution, but never actually offers a solution on how to do it. And the example in the linked article will run into problems if you want to make your form accept a dynamic number of nested objects. This is the only solution I've found

    https://coderwall.com/p/kvsbfa/nested-forms-with-activemodel-model-objects

    For posterity this is the basics, but there's a bit more on the site:

    class ContactListForm
    include ActiveModel::Model
    
    attr_accessor :contacts
    
    def contacts_attributes=(attributes)
      @contacts ||= []
      attributes.each do |i, contact_params|
        @contacts.push(Contact.new(contact_params))
      end
    end
    end
    
    class ContactsController < ApplicationController
       def new
          @contact_list = ContactListForm.new(contacts: [Contact.new])
        end
      end
    

    and f.fields_for :contacts should behave like an has_many relationship, and easily handled by your form object.

    If Contact isn't an AR model you'll need to spoof persisted? as well.

提交回复
热议问题