Skip to main content

Flexible Nested Attributes

Rails • Asked by Terence Devine

I'm working on a practice "Magazine" application, that has Issues with nested attributes of Articles, which has multiple nested attributes that are Content Blocks, which can be one of several types of Models (ie: Text Field, Image Upload, Image Gallery, etc).

Example
Issue

  • Article
  • - Content Block ( Text Field )
  • - Content Block ( Image )
  • - Content Block ( Text Field )
  • - Content Block ( Image Gallery )

In my head I've been referring to these Content Blocks as 'Flexible Nested Attributes'... not sure if theres any proper terminology for this?

I am using the Cocoon Gem for this.

I tried adding 'order_number' to Models, and just adding the two 'link_to_add_association' links as well as the respective fields for the form (see below) - and then ordering the two content types in the controller (see below-er)... which works, except for when I go to edit the form, and it orders all the items by their content type.

Do you know if the Cocoon gem can be used in this way? Or is there another gem I should be using (such as ActiveForm Gem)? Or if this is all wrong and maybe I should approach it some other way!?

Any help is greatly appreciated! Thanks!

= simple_form_for @recipe, html: { multipart: true } do |f|
    - if @recipe.errors.any?
        #errors
            %p
                = @recipe.errors.count
                Prevented this recipe from saving
            %ul
                - @recipe.errors.full_messages.each do |message|
                    %li= msg

    = f.input :title
    = f.input :description
    = f.input :image

    %h3 Contents
    #contents
        = f.simple_fields_for :images do |image|
            = render 'image_fields', f: image
        = f.simple_fields_for :textarea do |textarea|
            = render 'textarea_fields', f: textarea
        = link_to_add_association 'Add image', f, :images
        = link_to_add_association 'Add textarea', f, :textarea

    = f.button :submit
    def show
        @contents = @recipe.textarea + @recipe.images
        @contents = @contents.sort_by(&:order_number)
    end

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ 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.