Ruby on rails Rails:通过关联将属性值添加到has_many:中联接表中的几个新记录中
我有一个表格,它创建了一个新的运动,显示哪些肌肉群在工作。下面是我想输入DB的内容的示例: 新练习:名称=>上拉,主要=>背部,次要=>[二头肌,前臂,胸部] 我应该如何设置?我不想在muscle_groups_Executed表中存储primary和secondary作为数组,因为我将来有查询将基于该练习的主要muscle_组搜索练习 以下是应用程序此部分的架构:Ruby on rails Rails:通过关联将属性值添加到has_many:中联接表中的几个新记录中,ruby-on-rails,ruby,postgresql,Ruby On Rails,Ruby,Postgresql,我有一个表格,它创建了一个新的运动,显示哪些肌肉群在工作。下面是我想输入DB的内容的示例: 新练习:名称=>上拉,主要=>背部,次要=>[二头肌,前臂,胸部] 我应该如何设置?我不想在muscle_groups_Executed表中存储primary和secondary作为数组,因为我将来有查询将基于该练习的主要muscle_组搜索练习 以下是应用程序此部分的架构: create_table "exercises", force: true do |t| t.string "name
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
课堂练习
我有一个运动控制器和肌肉控制器。我认为这段代码应该存在于“运动控制者和肌肉组”的运动模型中,但并不确切知道如何做到这一点。您有更具体的问题吗?您的模式似乎适合您的需求。您可能不需要同时使用t.binary主项和t.binary次项——您可能不需要使用其中一个来指定该条目是主项还是次项。我认为您所做的是正确的。我想你会想将肌肉群应用到一项运动中,即使你以后要在肌肉群中搜索运动。我会将所需的代码放入
练习\u controller.rb
中
在HAMBTM复选框上,可以获得有关如何执行此操作的一些帮助。这并不完全是您正在做的,您需要为次要或主要应用附加值
顺便说一句,我不会为次要和主要设置两列,因为只有两个值,只要设置主要值,并假设如果不正确,则肌肉群是次要的。我不确定应该如何在控制器和/或模型中编写代码,因为我只对一对多关联执行了CRUD。我不知道如何为多对多协会做到这一点。有你可以指给我看的网页吗?