嵌套模型会抛出未定义的方法错误

时间:2010-08-29 02:37:16

标签: ruby-on-rails nested-forms

我一直在关注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

在我的WorkoutsController中,我有以下内容:

  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>

提前感谢您的帮助 - 我的RoR noobility不再让我感到惊讶!

修改: fflyer05:我尝试使用与RailsCast相同的代码来迭代集合,以及尝试在perform_exercises [0]上构建done_sets - 但它不起作用。做其他事情,我得到一个未初始化的常量PerformedExercise :: PerformedSet错误

1 个答案:

答案 0 :(得分:2)

应该在单个对象上调用模型方法。您在一个无效的对象集合上调用它们,@workout.performed_exercises[0].performed_sets将会。

注意来自Rails演员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

不起作用,我会检查以确保您的模型文件名是正确的(导轨需要它们是单数),在您的情况下,您应该workout.rbperformed_exercise.rb和{{1}对于那些相应的模型。

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