遍历参数时出错

Error while iterating through params

当我尝试遍历参数时出现错误

当运行代码如下:

def create_score
  @quiz = Test.find_by(password: session[:test_password])
  @points = 0
  @quiz.tasks.each_with_index do |task, index|
    @task = Task.find_by(id: task)
    @points += @task.score if @task.correct_answers.to_s == send("params[:test][:task#{index}]")
  end
  @score = Score.new(user_id: 2, name: "Test1", points: @points)
  if @score.save
    redirect_to root_url
  else
    redirect_to signup_path
  end
end

我得到:

undefined method `params[:test][:task0]' ...

@points += @task.score if @task.correct_answers.to_s == send("params[:test][:task#{index}]")

这意味着send方法有问题

参数如下所示:

{"utf8"=>"✓",
 "authenticity_token"=>"8h7rtv2yWio11DFo6kBKutdZl7RDBBaTrt7e8qel8fR5R5XsoXRhRrBeDQPPoZeuBlZ7N5PmqCxik06Z/gQLZQ==",
 "test"=>{"task0"=>["4"], "task1"=>["0"], "task2"=>["10"]},
 "commit"=>"Zakończ test",
 "locale"=>"pl"}

这意味着有params[:test][:task0],但由于某种原因它仍然会引发错误,但我真的不知道为什么。知道为什么会这样吗?

您正在使用 符号 调用您的 params,但您应该使用 字符串

这意味着您应该使用以下方法之一:

params["test"]["task0"] 要么 params[:test.to_s][:task0.to_s]

希望对您有所帮助:)

您想使用动态键索引,而不是动态调用方法。又名:

params[:test]["task#{index}"]

应该做的。请注意,参数对字符串和符号具有无差别的访问权限。


为了给你更多的思考空间,下面是你可以如何用 #send 做同样的事情:

params[:test].send(:[], "task#{index}")

下面是如何定义一个具有您要调用的名称的方法:

define_method("params[:test][:task#{index}]") do
  puts 'WTF'
end

您应该使用类似 params[:test][:task]) 的参数对象而不是 send("params[:test][:task#{index}]"