我不确定标题是否清楚。我不太确定我要寻找的答案是什么。我一直在寻找和寻找,但似乎找不到答案。
这是我想做的:
我希望用户创建包含 x 组、x 次数和 x 类型的锻炼。
例如,我知道我可以做到;
create_table "workouts", :force => true do |t|
t.string "workout name"
t.integer "sets"
t.integer "reps"
t.string "type"
end
但在这种方法中,它只允许写入/锻炼一种组。
我希望能够添加多种 类型的组/锻炼。
例如;
workout name: monday morning
sets: 2 reps: 4 type: "bicep curl"
sets: 4 reps 23 type: "bench press"
etc..
如果我的解释太不清楚或者我可能只是感到困惑,请随时指出。感谢所有帮助。感谢观看!
最佳答案
您应该创建一个表 workouts
和 workout_details
并将它们链接在一起:
create_table "workouts", :force => true do |t|
t.string :name
end
create_table "workout_details", :force => true do |t|
t.references :workout
t.integer :sets
t.integer :reps
t.string :type
end
你的模型看起来像这样:
class Workout < ActiveRecord::Base
has_many :workout_details
end
class WorkoutDetail < ActiveRecord::Base
belongs_to :workout
end
如果你这样设置,你会创建几个锻炼细节:
bicep_curl = WorkoutDetail.new
bicep_curl.type = 'bicep curl'
bicep_curl.sets = 2
bicep_curl.reps = 4
bicep_curl.save
bench_press = WorkoutDetail.new
bench_press.type = 'bench press'
bench_press.sets = 4
bench_press.reps = 23
bench_press.save
并将它们添加到锻炼中:
workout = Workout.new
workout.name = 'monday morning'
workout.workout_details << bicep_curl
workout.workout_details << bench_press
workout.save
要检索您的锻炼,您可以这样做:
workout = Workout.where(:name => 'monday morning').first
puts "workout name: #{workout.name}"
workout.workout_details.each do |wd|
puts "sets: #{wd.sets} reps: #{wd.reps} type: #{wd.type}"
end
输出:
workout name: monday morning
sets: 2 reps: 4 type: bicep curl
sets: 4 reps: 23 type: bench press
关于sql - "Flexible"(?) Rails 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17645577/