简体   繁体   中英

Rails Associations Planning

I'm still making my way with Rails and I have a question about associations.

I'm building a fitness website and I want to have users track their workouts. I'm a bit unsure as to how the associations should go. What follows is what I currently have.

A Workout is made up of a group of exercises. The user would create a workout object to save all the exercises together so as to not have to repeat the creation process every time. On top of that I don't want them to have to re-create exercises to add it to a new workout. So, both workouts and exercises would belong to a user.

My planned associations are this.

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

I think this is correct, but having both workout and exercise belonging to the user seems somewhat redundant to me. Is this the best setup or is there another way to associate these things? Any help is appreciated.

I see there is no need of having Routines there.And you need to tweak your Associations. How about like this

Workout

belongs_to :user
belongs_to :exercise

User

has_many :exercises
has_many :workouts :through => exercises

Exercise

has_many :workouts
belongs_to :user

Personally, this seems a bit more logical to me:

class User

  has_many :workouts

class Workout

  belongs_to :user
  has_and_belongs_to_many :exercises

class Exercise

  has_and_belongs_to_many :workouts

In my opinion exercises only belong to one or more workouts and it has little to do with an user. Therefore I would omit the association between users and exercises.

Since workouts can share similar exercises there is a many-to-many relationship between them. Usually I go for a has_many, through relationship in these cases, but since you do not mention possible additional attributes for the join model has_and_belongs_to_many with a join table should suffice.

EDIT: The associations are probably a bit more complex the more you think about it. For example, a workout can actually belong to multiple users. I think it would be best to go to the drawing board and draw the associations and the attributes per model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM