簡體   English   中英

rails model has_many:通過關聯

[英]rails model has_many :through associations

我試圖讓我的關系解決,但我在使用關聯時遇到了麻煩。

所以,我有三個型號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,以防萬一,所以你永遠不會錯。

你的代碼看起來不錯。 Bug也許has_and_belongs_to_many是更好的選擇。 請參閱選擇has_many:through和has_and_belongs_to_many

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM