【发布时间】:2017-01-17 15:31:43
【问题描述】:
当我尝试遍历参数时出现错误
运行以下代码时:
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],但由于某种原因它仍然会引发错误,但我真的不知道为什么。任何想法为什么会发生这种情况?
【问题讨论】:
标签: ruby-on-rails ruby metaprogramming