Skip to main content

Create form object with has_many attribute

Rails • Asked by Rafael Soares
Hi all,

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)?

I did some searching in google and surprisingly dind't find anything related to it

This doesn't appear to be maintained anymore, but there is an ActiveModel Associations gem you could use. https://github.com/joker1007/activemodel-associations

I've used it in the past for a complex form object like you're doing and you could mix this in easily with Cocoon or something to build out the child fields_for sections.

Might be worth a shot!

Have you looked at the different dynamic solutions for nested associations using cocoon?

https://github.com/nathanvda/cocoon

It may not be complete solution for what you are looking for - but unwrapping on the front-end is pretty straight-forward and cocoon can pretty decently handle the children associations and addition pretty well.  

*the neat part about cocoon is that it takes the complicated JS I used to roll up to make this same thing possible.
**I have been using cocoon with paperclip and amazon s3 to store documents that are associated with projects that our client's are working on and it works pretty flawlessly.  Just do not get crazy with paperclip if you do this - each resizing of an image is 2 or 3 calls to the tmp folder and imagemagick on the server, I just store everything at original size.

Hi guys, the problem is that both of these libraries need ActiveRecord to work with, and I'm using only ActiveModel

class Lesson
   include ActiveModel::Model
   attr_accessor :students

end

class Student
  attr_accessor :name
end

I have to make a nested form for this. The activemodel-associations gets close, but it still needs an ActiveRecord object in one end of the relation to work

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 20,000+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.