【发布时间】:2015-01-28 03:39:24
【问题描述】:
我的应用包含用户添加到锻炼中的锻炼。用户可以创建练习或选择现有练习。
*** 更新 **** 我根据 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..等感到困惑。
Rails 似乎正在寻找 ExercisesWorkout 类,但我定义了“exercises_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
错误:
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
【问题讨论】:
-
这个问题似乎与这个问题非常相似:stackoverflow.com/questions/9643128/…
-
谢谢,我最初实际上有那个链接。我认为我的情况不同,因为我没有连接表的模型。这似乎是这里的解决方案,而那里的解决方案与表配置有关。
标签: ruby-on-rails associations models