Rails Association策划

时间:2014-04-07 03:27:26

标签: ruby-on-rails activerecord ruby-on-rails-4 associations

我仍在使用Rails,我对协会有疑问。

我正在建立一个健身网站,我想让用户跟踪他们的锻炼。关于协会应该怎么做,我有点不确定。以下是我目前所拥有的。

锻炼由一组练习组成。用户将创建锻炼对象以将所有锻炼保存在一起,从而不必每次都重复创建过程。最重要的是,我不希望他们必须重新创建练习以将其添加到新的锻炼中。因此,锻炼和锻炼都属于用户。

我计划的协会就是这样。

Workout
belongs_to :user
has_many :exercises, :through => :routines

Exercise
belongs_to :user
has_many :workouts, :through => :routines

Routines
belongs_to :workout
belongs_to :exercise

User
has_many :workouts
has_many :exercises
//the rest of the user associations

我认为这是正确的,但是对于我而言,锻炼和锻炼属于用户似乎有点多余。这是最好的设置还是有其他方式来关联这些东西?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

我发现不需要Routines那里。你需要调整你的协会。 这样怎么样

Workout

belongs_to :user
belongs_to :exercise

User

has_many :exercises
has_many :workouts :through => exercises

Exercise

has_many :workouts
belongs_to :user

答案 1 :(得分:0)

就个人而言,这对我来说似乎更合乎逻辑:

class User

  has_many :workouts

class Workout

  belongs_to :user
  has_and_belongs_to_many :exercises

class Exercise

  has_and_belongs_to_many :workouts

在我看来,练习只属于一项或多项训练,与用户关系不大。因此,我会省略用户和练习之间的关联。

由于训练可以分享类似的练习,因此它们之间存在多对多的关系。通常我会在这些情况下通过关系找到has_many,但是因为你没有提到连接模型的可能的附加属性has_and_belongs_to_many和连接表就足够了。

编辑:你对它的思考越多,这种联想可能会有点复杂。例如,锻炼实际上可以属于多个用户。我认为最好去绘图板并绘制每个模型的关联和属性。