簡體   English   中英

遍歷參數時出錯

[英]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[:test]["task#{index}"]

應該做。 請注意,參數對於字符串和符號的訪問方式無關緊要。


為了給您更多思考的機會,您可以使用#send

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

這是如何定義一個將具有您要調用的名稱的方法:

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

您使用符號來調用params ,但是應該使用字符串

這意味着您應該使用以下方法之一:

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

希望有幫助:)

您應該使用params對象,例如params[:test][:task])而不是send("params[:test][:task#{index}]"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM