Search code examples
ruby-on-railsruby-on-rails-4nested-attributescocoon-gem

Prevent Cocoon from Loading Stored Objects


The Context:

I have a page in which I have a table of people. I would like to use cocoon to create what one might call a "quick-add" feature to the bottom of this table. Sounds simple enough, right?

The Catch:

For reasons beyond the scope of this question, I only want to be able to add people using this cocoon interface. I don't want to edit already-existing people, or delete them, or anything like that. I don't even want cocoon to load them. (I know, I know, it's a weird idea, right?)

The Question:

Is this something that I should use cocoon for, or would I be better off just writing my own javascript to add/remove these "quick-add" fields? If it's worth using cocoon, how can I implement it so that already-existing people aren't loaded from the database?

Thanks in advance.


Solution

  • Cocoon is not responsible for loading your associations. All you need to do is to omit fields_for part suggested in cocoon docs:

    = form_for @project do |f|
      .field
        = f.label :name
        %br
        = f.text_field :name
      .field
        = f.label :description
        %br
        = f.text_field :description
      %h3 Tasks
      #tasks
        -# Two lines below are responsible for displying already saved models. Just get rid of them.
        =# f.fields_for :tasks do |task|
          =# render 'task_fields', f: task
        .links
          = link_to_add_association 'add task', f, :tasks
      = f.submit
    

    Eventually, you might want your page to preserve newly inserted records in the form on validation error. In that case, fields_for accepts second param to specify records to be rendered:

    = f.fields_for :tasks, f.object.tasks.select(&:new_record?) do |task|
      = render 'task_fields', f: task