나는 관계를 완성하려고 노력하고 있지만 연관성을 사용하는 데 문제가 있습니다.레일 모델 has_many : 연관성을 통해
그래서 세 모델 Workout
, Exercise
및 WorkoutExercise
이 있습니다. 운동은 많은 연습을해야하고, 운동은 내가 쓴 때문에 다른 운동이 있어야합니다
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
이 정의되지 말한다 테스트합니다. 누구든지 아이디어가 있습니까?
마이그레이션을 실행 했습니까? 3 개의 테이블을 보여주십시오. 그리고 나는 Yanhao의 제안을 잠시 무시해야한다고 생각합니다. 코드가 올바르므로 지금은 변경하지 않아도됩니다. 너는 다른 것을 놓치고있다. – Ashitaka
@Ashitaka 위의 표를 추가했는데 CreateWorkoutExercises 테이블과 아무 관계가 없습니까? 이것은 처음으로 habtm을 사용하는 것입니다. – trev9065
그래, 그게 다야. 두 테이블 사이의 연결을 설정 한 ID가 누락되었습니다. 이제 마이그레이션을 재현하는 것이 좋습니다. 나는'rake db : reset'이 작업을 수행 할 것이라고 생각합니다. (모든 레코드를 삭제할 것입니다.) – Ashitaka