ruby-on-rails – rails模型has_many:通过关联
发布时间:2020-12-17 04:15:47 所属栏目:百科 来源:网络整理
导读:我试图让我的关系解决,但我在使用关联时遇到了麻烦. 所以我有三个模型锻炼,锻炼和锻炼锻炼.锻炼应该有很多锻炼,锻炼应该有不同的锻炼,因此我写道: class Workout ActiveRecord::Base has_many :workout_exercises has_many :exercises,:through = :workout_
我试图让我的关系解决,但我在使用关联时遇到了麻烦.
所以我有三个模型锻炼,锻炼和锻炼锻炼.锻炼应该有很多锻炼,锻炼应该有不同的锻炼,因此我写道: class Workout < ActiveRecord::Base has_many :workout_exercises has_many :exercises,:through => :workout_exercises end class Exercise < ActiveRecord::Base has_many :workout_exercises has_many :workouts,:through => :workout_exercises end class WorkoutExercise < ActiveRecord::Base belongs_to :exercise belongs_to :workout end 我正在运行一些测试,但是一旦我创建锻炼,锻炼然后将它们加入workout_exercise类中,测试就不会通过.它不会让我像这样访问锻炼中的练习: Workout.create Exercise.create WorkoutExercise.create(:workout => Workout.first,:exercise => Exercise.first) work = Workout.first work.exercises.count #This line causes the error: undefined method exercises 我的数据库表如下所示: class CreateWorkouts < ActiveRecord::Migration def change create_table :workouts do |t| t.string :title t.text :description t.float :score t.timestamps end end end class CreateExercises < ActiveRecord::Migration def change create_table :exercises do |t| t.string :title t.text :description t.float :value t.timestamps end end end class CreateWorkoutExercises < ActiveRecord::Migration def change create_table :workout_exercises do |t| t.timestamps end end end 当我运行此测试时,它表示练习未定义.有没有人有任何想法? 解决方法
好的,所以你的WorkoutExercises表不能为空.它应该是这样的:
class CreateWorkoutExercises < ActiveRecord::Migration def change create_table :WorkoutExercises do |t| t.integer :exercise_id,:null => false t.integer :workout_id,:null => false t.timestamps end # I only added theses indexes so theoretically your database queries are faster. # If you don't plan on having many records,you can leave these 2 lines out. add_index :WorkoutExercises,:exercise_id add_index :WorkoutExercises,:workout_id end end 此外,您可以根据需要为此表命名,它不必是WorkoutExercises. 因此,在这种情况下,您可以将您的表名为WorkoutExercises.但如果我是你,我会把它改为ExercisesWorkout,以防万一,所以你永远不会错. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |