2014-12-06 38 views
0

我有一个表单,它创建一个显示哪些肌肉群工作的新练习。这里是什么,我想进入DB的例子:Rails:将属性值添加到has_many:through关联中的连接表中的几条新记录

新运动:名称=>拉,主要=>回来,二次=> [二头肌,前臂,胸部]

我应该怎么设置这起来了吗?我不想将主要和次要数据存储在muscle_groups_exercised表中,因为我有将来的查询,将根据该练习的主要肌肉组搜索练习。

下面是应用程序,这部分的架构:

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 

下面是型号:

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 

我有一个exercises_controller和muscle_groups_controller。我认为这段代码应该存在于exercise_controller和muscle_groups_exercised模型中,但不完全相信如何做到这一点。

回答

1

你在做什么看起来很正确。我想象一下,即使你稍后要在肌肉群内搜索锻炼,也会想要将肌肉群应用于锻炼。我会把所需的代码放在exercises_controller.rb之内。

Check out Ryan Bates article and video对HAMBTM复选框的一些帮助如何做到这一点。这不完全是你在做什么,你将需要为中学或小学应用额外的价值。

顺便说一句,我不会有两列中学和小学,因为只有两个值,只有主要的假设,如果它不是真的,那么肌肉组是次要的。

0

您有更具体的问题吗?您的模式似乎适合您的要求。你可能不需要t.binary primary和t.binary secondary - 你可能会忽略它们中的一个来指定该条目是主要的还是次要的。

+0

我不知道我应该如何在控制器和/或模型中编写代码,因为我只对一对多关联进行过CRUD。我不知道如何为许多协会做到这一点。有没有可以指向我的网页? – HoodieOnRails 2014-12-06 06:46:00

相关问题