开发者

Nested models throws Undefined Method Error

I've been following RailsCast 197 to try this nested models/forms and have cracked my head over this code for over 2 hours, but to no avail. What am I overlooking?

I have the following Models:

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

In my WorkoutsController I have the following:

  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

When I run the test and invoke the controller in the browser, I get the following error:

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

Thanks in advance for any help - my RoR noobility ceases to amaze me!

Edit: fflyer05: I tried using the same code as the RailsCast with the iterating over the collection, as well as attempting to build the performed_sets on performed_exercises[0] - but开发者_如何学编程 it doesn't work. Doing anything else, I get an uninitialized constant PerformedExercise::PerformedSet error


Model methods should be called on a single object. You are calling them on a collection on objects which will not work, @workout.performed_exercises[0].performed_sets will.

Notice the code from the 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

You would have to loop through each nested method in order to build your form.

If code like this:


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

does not work, I would check to be sure that your model file names are correct (rails needs them to be singular) in your case you should have workout.rb,performed_exercise.rb and performed_set.rb for those respective models.

Your relationships' definitions look correct, so wrong file names is the only thing I can think of that can be wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜