0

I'm aiming to create blank questions, which are then assigned to editors to create.

To do this, I'm trying to create a form where I input the topic and the # of questions, and then have the backend iterate on that # to create x intentionally duplicate questions.

Controller:

def create
   @question = []
   5.times do
    @question = Question.new(question_params)
   end
  end

Params:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"unfqSHnfdNhidUCvLf3Zck8MeP59Qobe2bJz0tUhWQ1SUh29a8LdoGAYpUwbOOJS8U+wzlDQVBXQYcKeRqLDmQ==", "question"=>{"name"=>"four", "topic_id"=>"1"}, "commit"=>"Save "}

The above ideation only creates one record, I think because the controller is iterating, but only has one set of params input from the form.

Am I approaching this all wrong?

EDIT Full working controller for posterity, thx to the answer below.

controller do
def create
  if @question = 5.times.each_with_object([]) do |_, to_return|
    to_return << Question.create(question_params)
    end
    redirect_to admin_questions_path, notice: "Questions created"
  else
   # Handle failure
   redirect_to admin_questions_path, notice: "Questions NOT created"
  end
end
4

1 回答 1

1

更像是:

def create
  5.times.each_with_object([]) do |_, to_return|
    to_return << Question.create(question_params)
  end
end

这将返回一个包含所有使用相同的array5条记录的.@questionquestion_params

于 2018-08-17T21:19:41.270 回答