我的应用包含用户添加到锻炼中的练习。用户可以创建练习或选择现有练习。
***更新**** 我根据Ben的解决方案添加了一个模型。 在尝试向锻炼添加锻炼时,我收到如下错误。我的语法错了吗?我尝试过像this这样的解决方法:
w=Workout.last
e=Exercise.last
w.exercises.build(:exercise => e) # NameError: uninitialized constant Workout::ExercisesWorkout
w.exercises_workouts.create(:exericse_id => 1) #NameError: uninitialized constant Workout::ExercisesWorkout
我对协会附带的新方法以及“_”是否感到困惑,camelCase,Pluralize,symbol..etc。
Rails似乎在寻找班级ExercisesWorkout
,但我定义了“exercise_workouts”和/或ExercisesWorkouts。
感谢。
我在使用rails控制台向锻炼添加练习时遇到了麻烦。我看到2个潜在的问题:
请告诉我我的错误在哪里,以及是否有更好的结构/关联可供使用。
谢谢。
型号:
class Exercise < ActiveRecord::Base
has_many :workouts, :through => :exercises_workouts
has_many :exercises_workouts
end
class Workout < ActiveRecord::Base
has_many :exercises, :through => :exercises_workouts
has_many :exercises_workouts
end
class ExercisesWorkouts < ActiveRecord::Base
belongs_to :exercise
belongs_to :workout
end
schema.db:
ActiveRecord::Schema.define(version: 20141129181911) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "exercises", force: true do |t|
t.string "name"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "exercises_workouts", id: false, force: true do |t|
t.integer "exercise_id", null: false
t.integer "workout_id", null: false
end
create_table "workouts", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
ERROR:
w=Workout.new #create new workout
w.name = 'test' #name workout
w.save #save workout
e1=Exercise.new #create new exercise
e1.name='press' #name exercise
e1.save #save exercise
#I'm not sure of the syntax here... I've tried alot between create, build using symbols and finds...., this is just one example..
w.exercises.create(e1) #NameError: uninitialized constant Workout::ExercisesWorkout
答案 0 :(得分:0)
您还需要连接表的模型:
class ExercisesWorkouts < ActiveRecord::Base
belongs_to :exercise
belongs_to :workout
end
如果您有兴趣,以下是更详细地介绍联接表的答案:
What would the joining table called in this case in Rails 3.1?