【发布时间】:2020-01-06 19:03:50
【问题描述】:
我正在构建一个锻炼跟踪应用程序。目前,我的模型是这样设置的...... 一个用户有_很多时间表 有很多锻炼的时间表 锻炼有很多锻炼 一个练习 has_many 电路(包括代表/组/重量)。
一切正常。
但现在我正在添加一个新的关系,我不确定如何设置。 我想要一个新模型,用户 has_many "completed_workouts" 包含锻炼模型的所有属性。
我的第一个想法是添加一个 user_workout 模型;为用户和锻炼提供外键。但这意味着每当我对锻炼进行更改时,它也会反映在 user.workouts 中;这不是我想要的。
schema.rb
create_table "circuits", force: :cascade do |t|
t.integer "weight"
t.integer "reps"
t.integer "rest"
t.integer "exercise_id"
end
create_table "exercises", force: :cascade do |t|
t.string "name"
end
create_table "schedules", force: :cascade do |t|
t.string "name"
end
create_table "user_schedules", force: :cascade do |t|
t.integer "user_id"
t.integer "schedule_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "username"
end
create_table "workout_exercises", force: :cascade do |t|
t.integer "workout_id"
t.integer "exercise_id"
end
create_table "workout_schedules", force: :cascade do |t|
t.integer "workout_id"
t.integer "schedule_id"
end
create_table "workouts", force: :cascade do |t|
t.string "name"
end
user.rb
class User < ApplicationRecord
has_many :user_schedules
has_many :schedules, through: :user_schedules
end
schedule.rb
class Schedule < ApplicationRecord
has_many :user_schedules
has_many :users, through: :user_schedules
has_many :workout_schedules
has_many :workouts,through: :workout_schedules
accepts_nested_attributes_for :workouts
end
锻炼.rb
class Workout < ApplicationRecord
has_many :workout_exercises
has_many :exercises,through: :workout_exercises
has_many :workout_schedules
has_many :schedules,through: :workout_schedules
end
【问题讨论】:
标签: ruby-on-rails foreign-keys relational-database