HoodieOnRails
HoodieOnRails

Reputation: 248

Rails: Add attribute values to several new records in a join table in a has_many :through association

I have a form that creates a new exercise showing which muscle groups are worked. Here's an example of what I want to enter into the DB:

New exercise: name => Pull-up, primary => back, secondary => [biceps, forearms, chest]

How should I set this up? I don't want to store primary and secondary as arrays in the muscle_groups_exercised table because I have future queries that will search for exercises based on a muscle_group that is primary to that exercise.

Here is the schema for this part of the app:

create_table "exercises", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "muscle_groups", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "muscle_groups_exercised", force: true do |t|
    t.integer "muscle_group_id"
    t.integer "exercise_id"
    t.binary  "primary"
    t.binary  "secondary"
end

 add_index "muscle_groups_exercised", ["exercise_id"], name: "index_muscle_groups_exercised_on_exercise_id", using: :btree
 add_index "muscle_groups_exercised", ["muscle_group_id"], name: "index_muscle_groups_exercised_on_muscle_group_id", using: :btree

Here are the models:

class Exercise < ActiveRecord::Base
  has_many :muscle_groups, through: :muscle_groups_exercised
end

class MuscleGroup < ActiveRecord::Base
  has_many :exercises, through: :muscle_groups_exercised
end

class MuscleGroupExercised < ActiveRecord::Base
  belongs_to :exercise
  belongs_to :muscle_group
end

I have an exercises_controller and muscle_groups_controller. I think this code should reside in the exercises_controller and muscle_groups_exercised model but not exactly sure how to do this.

Upvotes: 0

Views: 48

Answers (2)

Ken Stipek
Ken Stipek

Reputation: 1522

What you are doing looks right to me. I imagine will want to apply muscle groups to an exercise, even if you are going to be searching within muscle groups for exercises later on. I would put the required code within exercises_controller.rb.

Check out Ryan Bates article and video on HAMBTM checkboxes for some help on how to do this. It isn't exactly what you are doing, you will need to apply an additional value for secondary or primary.

BTW, I wouldn't have two columns for secondary and primary, since there is only two values, just have the primary one and assume if it isn't true, then the muscle group is secondary.

Upvotes: 1

johnklawlor
johnklawlor

Reputation: 1988

Do you have a more specific question? Your schema seems appropriate for your requirements. You may not need both a t.binary primary and a t.binary secondary--you could probably get away with having just one of them to specify whether that entry is primary or secondary.

Upvotes: 0

Related Questions