【问题标题】:ActiveModel::MissingAttributeError in Controller can't write unknown attribute控制器中的 ActiveModel::MissingAttributeError 无法写入未知属性
【发布时间】:2015-08-16 21:17:04
【问题描述】:

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

MemoMainTesterController#test_students 中的 ActiveModel::MissingAttributeError 无法写入未知属性current_target

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

它专门出现在student[:current_target] = current[0] 的位置。

我不能在这个哈希上附加额外的值吗? 有解决办法吗?

编辑:虽然Student.all 是一个模型实例,但我想把它变成一个散列并附加更多的键值对。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord backend


    【解决方案1】:

    在您的情况下,student 不是 Hash,而是 Student 模型实例。

    当您调用student[:current_target] 时,您正在尝试编写学生的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
    

    【讨论】:

    • 我不知道你到底想达到什么目的。你能更新你的问题吗?
    • 虽然Student.all是一个模型实例,但我想把它变成一个hash,并给它附加更多的键值对。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多