gpt4 book ai didi

ruby-on-rails - rails 模型 has_many :through associations

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:00 24 4
gpt4 key购买 nike

我正在努力解决我的人际关系,但我在使用关联时遇到了问题。

所以我有三个模型WorkoutExerciseWorkoutExercise。一个锻炼应该有很多练习,一个锻炼应该有不同的锻炼,因此我写道:

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

当我运行这个测试时,它说 exercises 是未定义的。有人有什么想法吗?

最佳答案

好的,所以您的 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。但是,如果您使用 has_and_belongs_to_many 关系,您的表必须强制命名为 ExercisesWorkout。注意锻炼是如何出现在锻炼之前的。名称必须按字母顺序排列。不要问我为什么,这只是一个 Rails 约定。

因此,在这种情况下,您可以将表格命名为 WorkoutExercises。但如果我是你,我会把它改成 ExercisesWorkout,以防万一,这样你就不会弄错了。

关于ruby-on-rails - rails 模型 has_many :through associations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com