【问题标题】:Error while iterating through params遍历参数时出错
【发布时间】: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


    【解决方案1】:

    您希望使用动态键进行索引,而不是动态调用方法。又名:

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

    应该这样做。请注意,params 对字符串和符号的访问权限无关紧要。


    为了让您深思熟虑,以下是您可能对#send 进行相同操作的方法:

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

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

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

    【讨论】:

    • 值得一提的是,字符串插值不能直接与符号一起使用
    【解决方案2】:

    您使用 symbol 调用 params,但您应该使用 string

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

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

    希望有所帮助:)

    【讨论】:

    • 来自rails docs:“params 对象的作用类似于 Hash,但您可以将符号和字符串互换地用作键。”
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 2014-12-24
      • 2023-04-10
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多