【问题标题】:Errors when using Rails has_many :through association使用 Rails has_many 时的错误:通过关联
【发布时间】: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 个潜在问题:

  1. 我不知道执行此操作的正确语法(构建、创建、查找)
  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


【解决方案1】:

您还需要一个连接表的模型:

class ExercisesWorkouts < ActiveRecord::Base
    belongs_to :exercise
    belongs_to :workout
end

如果您有兴趣,这里是更详细地涵盖连接表的答案:

What would the joining table called in this case in Rails 3.1?

【讨论】:

  • 感谢您的指导。我以为我读到连接表不一定需要该模型。我很快就会测试。
  • @twinturbotom has_and_belongs_to_many 不需要该模型。只有has_many :through 需要它。 (当然db中的join表总是需要的)
  • Ben,我认为这可以解决关联问题(问题 2 of 2),但我仍然收到错误消息。您能否说明在锻炼中添加练习的语法应该如何(问题 1,共 2 题)。在这里感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-05-06
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 2015-01-27
相关资源
最近更新 更多