0

I often use form objects in some places in my application. But what I need now is something a little more complex.

When I create them, it's always an ActiveModel object with simple string attributes. But what I need now is for this object to have nested objects in them.

Ex: I have a ClassroomForm object, which has simple attributes such as name and teacher_id. But this Classroom object can have many student object, which has fields such as name and status.

What is the best way to do it using ActiveModel? Is the solution to create two form objects, ClassroomForm and StudentsForm, and then in ClassroomForm declare a attr_accessor :students ? But then how can I add new students in the form (using nested attributes)?

rafilsk
  • 1
  • 1
  • Refer this : https://stackoverflow.com/questions/27682951/rails-4-nested-form-with-accepts-nested-attributes-for-controller-setup – Deepak Mahakale Mar 22 '18 at 14:00
  • There's a good guide here: https://www.sitepoint.com/complex-rails-forms-with-nested-attributes/ If you work through that you should find everything you need. – SRack Mar 22 '18 at 14:02
  • These examples use ActiveRecord objects, which I'm aware how to use it. The problem here is that I need to do with ActiveModel objects – rafilsk Mar 24 '18 at 12:27

1 Answers1

1

Go for nested attributes

As per your example: First add accepts_nested_attributes_for :students_forms, allow_destroy: true to your ClassroomForm model and then use form builder to render student forms

don't forget to add builder.hidden_field :_destroy for deletion of student_forms directly from the classroom form

NRaghavendra
  • 126
  • 1
  • 7
  • Probably worth adding something about using `simple_fields_for` and how to handle the strong params? Feels a little incomplete without these bits. – SRack Mar 22 '18 at 14:19
  • I don't think that's necessary because the requirement is to give a brief idea to usage process, but a worthy mention @SRack – NRaghavendra Mar 23 '18 at 07:34