Create Multiple records with fields_for - Rails

后端 未结 1 1800
盖世英雄少女心
盖世英雄少女心 2021-01-28 04:00

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

相关标签:
1条回答
  • 2021-01-28 04:34

    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.

    0 讨论(0)
提交回复
热议问题