Bitwise
Bitwise

Reputation: 8461

Create Multiple records with fields_for - Rails

I have two models, task and list_items. a task has_many list_items. But I want to be able to be able to create task and many list_items if the user wants all in one form. Here is what it looks like currently:

FORM

<%= form_for @task, url: account_assignment_tasks_path(@assignment), method: :create do |form| %>
  <%= form.text_field :description, class: "form-input #{error_class}" %>

  <%= fields_for :list_items, @all_list_items do |list_item_form| %>
      <%= list_item_form.text_field :description, class: "form-input list-item", data: { list_item_field: "true" } %>
    <% end %>
<% end %>

Task Controller

 def new
   @task = @assignment.tasks.new
   @list_item = @task.list_items.build
   @all_list_items = []
 end

Basically what I'm trying to do is create multiple list items and one task on create. But right now I'm getting this error if I submit the form

ERROR

undefined method `description' for []:Array

Does anybody know what I'm doing wrong and how I can achieve this?

Upvotes: 0

Views: 1478

Answers (1)

Pavan
Pavan

Reputation: 33542

undefined method `description' for []:Array

To describe the reason for the error, fields_for accepts record_object as a second parameter which fields_for uses it to construct the fields. Here you are passing @all_list_items which is an array and that results in the error.

Solution to the error:

You should pass @list_item instead of @all_list_items

<%= fields_for :list_items, @list_item do |list_item_form| %>

Solution to the actual problem:

As you want to create multiple list_items, you should do

def new
  @task = @assignment.tasks.new
  x.times do
    @list_item = @task.list_items.build
  end
  @all_list_items = []
end

where x is how many list_items you want to create, for example if you want to create three list_items, then replace x with 3.

OR

Use cocoon gem to dynamically create nested forms.

Upvotes: 2

Related Questions