2015-12-24 145 views
0

选择我有一个Workout模型:红宝石没有右表

class Workout < ActiveRecord::Base 
    has_one :exercise 

    belongs_to :session 
    has_many :exercise_equipment 

end 

Exercise模型

class Exercise < ActiveRecord::Base 
    has_many :workouts 
end 

,并在我的show我有@workout.exercise.name它抛出一个SQLException:

no such column: exercises.exercise_id: SELECT "exercises".* FROM "exercises" WHERE "exercises"."exercise_id" = ? LIMIT 1 

尽管读了一些si milar的帖子,我真的不明白,为什么似乎SELECT exercises FROM exercises这个has_one :exercise行的结果并没有任何意义,我会假设,因为我使用的是Workout对象,它会检查在workouts表我

我试过

has_one :exercise, :class_name => 'Workout', :foreign_key => 'exercise_id' 

但后来我得到​​

add_foreign_key :workouts, :exercises 
add_foreign_key :exercises, :workouts 

没有运气,巴克。

所以有人可以向我解释一下Ruby/Rails认为它在做什么以及我如何避免这个令人困惑的问题?

exercises 
    id:integer 
    name:text 
    description:text 
    created_at:text 
    updated_at:text 

workouts 
    id:integer 
    name:text 
    exercise_id:integer 
    session_id:integer 
    created_at:text 
    updated_at:text 
+0

如果您在锻炼中有has_one或has_many,则必须在所引用的关联上有workout_id。关联模型将具有“belongs_to:锻炼” – Swards

+0

尽管锻炼独立于锻炼而存在。我应该可以进行“跳跃杰克”运动,而不必说出哪些人的训练参考了运动,对吧?所以我仍然不确定它为什么试图从练习表中选择exercise_id。 – Csteele5

+0

一次锻炼是否有很多锻炼?还是只有一个? – Swards

回答

1

你只是想改变这对锻炼

has_one :exercise 

belongs_to :exercise 

belongs_to去与表t帽子上有foreign_key。

+0

这可行,但我有几个问题。有两个这样的belongs_to关系可以吗?这是否意味着对于has_many和has_ones,您不需要提供外键? – Csteele5

+0

是的,你可以 - “belongs_to”真的只是给你一堆期望外键在对象上的方法。 http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to你将拥有许多belongs_to,因为你在数据库中有外键。 'has_one'很少见。 – Swards

1

您不必在Ruby中指定的外键,如果他们的名字是ENTITY_ID。如果你想有N个锻炼的一个练习所有你需要做的是让列锻炼表exercise_id然后指定型号:

class Workout < ActiveRecord::Base 
    has_one :exercise 
end 

class Exercise < ActiveRecord::Base 
    has_many :workouts 
end 
+0

我错打了我的模特,我已经尝试过他们,就像这样。这是行不通的。 – Csteele5

+0

你可以更新模型并将数据库模式添加到原始文章中吗? – piko