Ruby on rails 使用Rails时的错误有很多:通过关联

Ruby on rails 使用Rails时的错误有很多:通过关联,ruby-on-rails,associations,models,Ruby On Rails,Associations,Models,我的应用程序由用户添加到训练中的练习组成。用户可以创建练习或选择现有练习 ***更新**** 我根据Ben的解决方案添加了一个模型。 在尝试将练习添加到训练中时,我收到如下错误。我的语法错了吗?我尝试过以下解决方法: 我被协会附加的新方法弄糊涂了,还有“uu”与否,camelCase,Pluralize,symbol…等等 Rails似乎在寻找类ExercisesWorkout,但我定义了“exercise\u-workouts”和/或ExercisesWorkouts 谢谢 我无法从rail

我的应用程序由用户添加到训练中的练习组成。用户可以创建练习或选择现有练习

***更新**** 我根据Ben的解决方案添加了一个模型。 在尝试将练习添加到训练中时,我收到如下错误。我的语法错了吗?我尝试过以下解决方法:

我被协会附加的新方法弄糊涂了,还有“uu”与否,camelCase,Pluralize,symbol…等等

Rails似乎在寻找类
ExercisesWorkout
,但我定义了“exercise\u-workouts”和/或ExercisesWorkouts

谢谢


我无法从rails控制台向训练添加练习。我看到的2个潜在问题:

  • 我不知道做这件事的正确语法(build、create、find)
  • 正确设置应用程序(联接表、模型等)
  • 请让我知道我的错误在哪里,以及是否有更好的结构/关联可供使用

    多谢各位

    型号:

    class Exercise < ActiveRecord::Base
        has_many :workouts, :through => :exercises_workouts
        has_many :exercises_workouts
    end
    
    
    class Workout < ActiveRecord::Base
        has_many :exercises, :through => :exercises_workouts
        has_many :exercises_workouts
    end
    
    class ExercisesWorkouts < ActiveRecord::Base
        belongs_to :exercise
        belongs_to :workout
    end
    
    错误:

     w=Workout.new #create new workout
     w.name = 'test' #name workout
     w.save #save workout
    
     e1=Exercise.new #create new exercise
     e1.name='press' #name exercise
     e1.save #save exercise
    
    #I'm not sure of the syntax here... I've tried alot between create, build using symbols and finds...., this is just one example.. 
     w.exercises.create(e1) #NameError: uninitialized constant Workout::ExercisesWorkout
    

    您还需要联接表的模型:

    class ExercisesWorkouts < ActiveRecord::Base
        belongs_to :exercise
        belongs_to :workout
    end
    
    class ExercisesWorkouts
    如果您感兴趣,下面是更详细地介绍联接表的答案:


    这个问题似乎与这个问题非常相似:谢谢,我一开始确实有这个链接。我认为我的情况不同,因为我没有联接表的模型。这可能就是这里的解决方案,而那里的解决方案与表配置相关。感谢您的指导。我想我读到了连接表不一定需要这个模型。我将很快进行测试。@twinturbotom该模型不需要用于
    has\u和\u属于\u many
    。仅当
    有多个:通过
    时才需要它。(当然,数据库中的连接表总是必需的)Ben,我认为这修复了关联(问题2/2),但我仍然收到错误。您能否说明将练习添加到训练中的语法应该是什么样的(问题1/2)。谢谢你在这里的帮助!
    
     w=Workout.new #create new workout
     w.name = 'test' #name workout
     w.save #save workout
    
     e1=Exercise.new #create new exercise
     e1.name='press' #name exercise
     e1.save #save exercise
    
    #I'm not sure of the syntax here... I've tried alot between create, build using symbols and finds...., this is just one example.. 
     w.exercises.create(e1) #NameError: uninitialized constant Workout::ExercisesWorkout
    
    class ExercisesWorkouts < ActiveRecord::Base
        belongs_to :exercise
        belongs_to :workout
    end