2010-08-29 82 views
0

我一直在關注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與遍歷集合,並試圖建立在performed_exercises的performed_sets [0] - 但它不工作。做任何事情,我得到一個未初始化的常量PerformedExercise :: PerformedSet錯誤

回答

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.rbperformed_set.rb這些相應的型號。

您的關係的定義看起來是正確的,所以錯誤的文件名是我能想到的唯一可能是錯誤的。

+0

非常感謝soooo fflyer05。我的PerformedSet模型文件名是perform_sets。 – MunkiPhD 2010-08-29 14:50:00

相關問題