rails model has_many :through associations

后端 未结 2 1339
野性不改
野性不改 2021-01-05 05:34

I am trying to get my relationships worked out but I am having trouble using the associations.

So I have three models Workout, Exercise and

相关标签:
2条回答
  • 2021-01-05 05:56

    Your code looks OK. Bug maybe has_and_belongs_to_many is a better choice. See Choosing Between has_many :through and has_and_belongs_to_many

    0 讨论(0)
  • 2021-01-05 06:02

    Ok, so your WorkoutExercises table can't be empty. This is how it should look:

    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
    

    Also, you can name this table whatever you'd like, it doesn't have to be WorkoutExercises. However, if you were using a has_and_belongs_to_many relationship, your table would have to mandatorily be named ExercisesWorkout. Notice how Exercises comes before Workout. The names have to be alphabetically ordered. Don't ask me why, it's just a Rails convention.

    So, in this case, you'll do fine with your table being named WorkoutExercises. But if I were you, I'd change it to ExercisesWorkout, just in case, so that you never get it wrong.

    0 讨论(0)
提交回复
热议问题