Friday, 4 November 2011

Bits of Code - Nested Attributes

Yesterday I had the need to implement a form with some nested attributes and so I did what I often do: I went back to a previous project and copy&pasted the necessary code and then changed it to match the new project's needs.

While I was doing this I thought that it would be useful to get this, and other bits of code in a place that I can easily refer to, instead of having to remember in which project I've used what. This is the reasoning behind this post.

Bare in mind that this is not a post about life changing bits of code, but rather bits of code that I need now and then and that are easier to just copy&paste&edit than to have to rewrite from scratch. Some of these bits can be easily found in different websites, but having them here will make my life easier than having to search again. I'll make sure I'll refer to the websites that I've used.

So these first bits of code are meant to build a form with nested attributes.

Imagine that you have a model named Content that has many Attachments and when you are adding or editing a content, you want to be able to manage that content's attachments. This allows you to easily do it.

This code uses Rails accepts_nested_attributes_for and then it manages the different attachments with javascript methods (using jQuery framework), allowing you to add, remove and edit them accordingly.

The Content model:

The Attachment model (notice the accepts_nested_attributes_for method):

The ApplicationHelper, with the methods used in the views:

Part of the Content form view (notice the use of the method fields_for, and the helper method link_to_add_fields):

The attachment_fields partial (notice the use of the helper method link_to_remove_field):

And the javascript methods (notice that if the position of the elements in the attachment_fields partial changes this code might need to be updated):

 These bits of code are based on (or were copied from):

No comments:

Post a Comment