Skip to content

Instantly share code, notes, and snippets.

@tonatiuh
Created January 28, 2014 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonatiuh/8672046 to your computer and use it in GitHub Desktop.
Save tonatiuh/8672046 to your computer and use it in GitHub Desktop.

Easy Nested Forms with Rails

Introduction

  • What are nested forms?
    • Forms that allow you to save information not only for a base element, but for related elements of the main element

Basic Form

  • Someone is asking for a SalesOrder Form in which the client name can be set (as plain text)
  • What is required to accomplish that?
    • SalesOrder model

        class SalesOrder < ActiveRecord::Base
          # Allows to set a name
        end
    • View for displaying the form

        = form_for :sales_order do |sof|
          = sof.label_field :name
          = sof.text_field :name
          = sof.submit
    • SalesOrder info processing in the controller

        class SalesOrdersController
          def create
            sales_order = params[:sales_order]
            sales_order.save
          end
        end

Nested Form

  • Suddenly, that someone is asking for allowing to save a Product for a Salesorder
  • What is required to accomplish it?
    • Models

      • Product model

          class Product < ActiveRecord::Base
            belongs_to :sales_order
          end
        
      • SalesOrder model

          class SalesOrder < ActiveRecord::Base
            has_many :products
            accepts_nested_attributes_for :products
          end
        
    • View for displaying the form

        = form_for :sales_order do |sof|
          - #other content
          = sof.fields_for :product do |pf|
            = pf. :name
            = pf.text_field :name
          = sof.submit
    • SalesOrder info processing in the controller

        class SalesOrdersController
          def create
            sales_order = params[:sales_order]
            sales_order.save
          end
        end
      • The same than in the previous example!

Can Rails handle complex forms?

  • Complex Nested Forms can be accomplished:
    • For instance, to have a SalesOrder Form having a Product having ProductVariant
    • Nested Forms addition in Real Time
      • As many as needed
      • You can take advantage of the "unobstrusive javascript" feature from Rails
        • You add the fewer JS required, which makes even easier to maintain the forms

Conclusion

  • As we seen, Rails Nested Forms are very practical, easy to setup, and to maintain
  • Also, Rails handles the params by you, so you don't have to worry about that
  • A very viable option for implementing Nested Forms when working on a Rails App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment