[SOLVED] rails: how can we add multiple valued params in db in one query in rails?

Issue

This Content is from Stack Overflow. Question asked by kashif mehmood

consider i have these attributes in table:
answers, user_id, question_id

This is what i did:
i stored it with the loop but thats bad practice to trigger database again and again:
temp= params.fetch(:user_answer)
temp[“answers”].length.times { |i|
UserAnswer.create!(answers: temp[“answers”][i], question_id: temp[“question_id”][i], student_id: current_user.id)
}

i have values in my params like this:
“user_answer”=>{“answers”=>[“C++ is mother of all the languages”, “25”], “question_id”=>[“7”, “10”], “student_id”=>[“12”, “12”]}

how can i add multiple records in one query with this params?



Solution

You can pass to create array of arguments

But firstly you need to create such array

user_answer_args =
  params[:user_answer].each_with_object([]) do |(param, values), args|
    values.each_with_index do |value, index|
      args[index] ||= {}
      args[index].merge!(param => value)
    end
  end

And than

UserAnswer.create(user_answer_args)

Note: you need to convert params to hash firstly, something like this

user_answer_params =
  params.
    require(:user_answer).
    permit(answers: [], question_id: [], student_id: []).
    to_h


This Question was asked in StackOverflow by kashif mehmood and Answered by mechnicov It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?