代码之家  ›  专栏  ›  技术社区  ›  MunkiPhD

嵌套模型引发未定义的方法错误

  •  0
  • MunkiPhD  · 技术社区  · 14 年前

    我一直在跟踪 RailsCast 197 尝试这种嵌套的模型/表单,并且在这段代码上花了2个多小时的时间破解了我的头,但是没有用。我忽略了什么?

    我有以下型号:

    class Workout < ActiveRecord::Base
      belongs_to :user
      has_many :performed_exercises, :dependent => :destroy
      accepts_nested_attributes_for :performed_exercises
    end
    
    class PerformedExercise < ActiveRecord::Base
      belongs_to :workout
      belongs_to :exercise
      has_many :performed_sets, :dependent => :destroy
      accepts_nested_attributes_for :performed_sets
    end
    
    class PerformedSet < ActiveRecord::Base
      belongs_to :performed_exercise
    end
    

    在我的WorkoutController中,我有以下功能:

      def new
        # We only need to build one of each since they will be added dynamically
        @workout = Workout.new
        @workout.performed_exercises.build
        @workout.performed_exercises.performed_sets.build
      end
    

    当我运行测试并在浏览器中调用控制器时,会得到以下错误:

    undefined method `performed_sets' for #<Class:0x7f6ef6fa6560>
    

    提前感谢你的帮助-我的错误不再让我惊讶!

    编辑 : fflyer05:我尝试使用与RailsCast相同的代码对集合进行迭代,并尝试在已执行的\练习[0]上构建已执行的\集,但它不起作用。执行其他操作时,会得到一个未初始化的常量PerformedExercise::PerformedSet错误

    1 回复  |  直到 14 年前
        1
  •  2
  •   fflyer05    14 年前

    应在单个对象上调用模型方法。您正在对不起作用的对象的集合调用它们, @workout.performed_exercises[0].performed_sets 威尔。

    请注意Rails Cast 196中的代码:

    
    # surveys_controller.rb
    def new
      @survey = Survey.new
      3.times do
        question = @survey.questions.build
        4.times { question.answers.build }
      end
    end
    
    

    为了构建表单,您必须遍历每个嵌套方法。

    如果代码如下:

    
    for performed_exercise in @workout.performed_exercises
         for performed_set in performed_exercise.performed_sets
          # something interesting
         end
    end
    
    

    不起作用,我会检查以确保您的模型文件名是正确的(Rails需要它们是唯一的),在您的情况下,您应该 workout.rb , performed_exercise.rb performed_set.rb 对于这些型号。

    你的关系定义看起来是正确的,所以我唯一能想到的就是错误的文件名。