Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveModel::控制器can中缺少属性错误';不写入未知属性_Ruby On Rails_Ruby_Activerecord_Backend - Fatal编程技术网

Ruby on rails ActiveModel::控制器can中缺少属性错误';不写入未知属性

Ruby on rails ActiveModel::控制器can中缺少属性错误';不写入未知属性,ruby-on-rails,ruby,activerecord,backend,Ruby On Rails,Ruby,Activerecord,Backend,对于rails应用程序中的一个视图,我已经设置了控制器。我想从数据库中获取所有学生的记录,并向每个学生附加额外的值。这给了我一个错误: ActiveModel::MemoMainTesterController中缺少属性错误测试学生 无法写入未知属性当前\u目标 class MemoMainTesterController < ApplicationController def test_students @all_students = Student.all @all

对于rails应用程序中的一个视图,我已经设置了控制器。我想从数据库中获取所有学生的记录,并向每个学生附加额外的值。这给了我一个错误:

ActiveModel::MemoMainTesterController中缺少属性错误测试学生 无法写入未知属性
当前\u目标

class MemoMainTesterController < ApplicationController
  def test_students
    @all_students = Student.all
    @all_students.each do |student|
      current = current_target(student)
      previous_test_info = last_pass(student)
      student[:current_target] = current[0]
      student[:current_level] = current[1]
      student[:current_target_string] = "Level #{current[0]} - Target #{current[1]}"
      student[:last_pass] = previous_test_info[0]
      student[:attempts] = previous_test_info[1]
      student[:last_pass_string] = previous_test_info[2]
    end
  end
.
.
.
end
class MemoMainTesterController
它特别出现在
student[:current\u target]=current[0]
的位置

不允许我向该散列追加额外值吗? 有解决办法吗


编辑:虽然
Student.all
是一个模型实例,但我想将其转换为哈希并向其附加更多的键值对。

在您的例子中,
Student
不是哈希而是
Student
模型实例

调用
student[:current_target]
时,您试图写入student的
current_target
属性,该属性肯定不是
students
表中的实际属性。因此出现了错误

从包含额外数据的模型中获得散列,您可以考虑此重构:

class MemoMainTesterController < ApplicationController
  def test_students
    @all_students = Student.all
    @students_with_steroids = @all_students.map do |student|
      current            = current_target(student)
      previous_test_info = last_pass(student)
      student_attributes = student.attributes # <= this is a hash, that you store in student_attributes hash variable

      student_attributes.merge(current_target: current[0], 
        current_level: current[1], 
        current_target_string: "Level #{current[0]} - Target #{current[1]}",
        last_pass: previous_test_info[0],
        attempts: previous_test_info[1],
        last_pass_string: previous_test_info[2])
    end
  end
class MemoMainTesterControllerstudent_attributes=student.attributes#我不知道你到底想达到什么目的。你能更新你的问题吗?虽然
Student.all
是一个模型实例,但我想把它变成一个散列,并向它附加更多的键值对。