使用相同的 :id 在数据库中创建多个记录

Create multiple records in the database with same :id

我正在尝试在我的 rails 应用程序上创建同一条记录的多个实例。我有 testsquestionstests 可以有很多 questions

我也有testsessions。我的 testsessions table 看起来像这样:

id | user_id | test_id | question_id | answer

我试图让控制器创建同一个测试会话的多个实例,唯一不同的是 question_id,它将从具有相同 test_id 的问题中提取作为测试环节。

目前我的控制器中有这个:

def new
  @test = Test.find(params[:test_id])
  @testsession = @test.testsessions.new
  @testsession.user_id = current_user.id

  @testsession.save
  @questions = @test.questions
  redirect_to action: :index
end

但我不知道如何让它根据 question_id.

创建多个实例

我有一个要使用的 question_id 数组:

@questions = Question.where(test_id: @test.id).pluck(:id)

但我不知道如何将其放入控制器...最后我希望 table 看起来像这样:

id | user_id | test_id | question_id | answer
1  |    1    |    1    |      1      |
1  |    1    |    1    |      2      |
1  |    1    |    1    |      3      |
1  |    1    |    1    |      4      |

答案始终为空,因为这将由用户稍后使用 update

输入

任何关于如何做到这一点的想法将不胜感激!

我想我明白你想要达到的目标:你有一个 has_many 问题的测试。当有人做测试时,您想提前为每个问题创建一个测试会话。

试试这个:

def new
  @test = Test.find(params[:test_id])

  @test.questions.each do |question|
    @test.testsessions.create user: current_user, question: question
  end

  redirect_to action: :index
end

附带说明:new 控制器操作并不是创建内容的好地方,因为 new(通常)可通过 HTTP GET 请求访问。

暂时假设您编写的应用可供 Google 访问。如果 Google 找到此控制器操作的 link,它将访问它并意外地创建新的测试会话对象。可能很多次。

这就是为什么在您的应用程序中创建或更改某些内容的控制器操作只能通过其他方法访问,例如 POST — 搜索引擎和其他机器人不会触及这些。

即使您的应用在 public 中无法访问,养成习惯也是一个好习惯。