ruby-on-rails - 无法通过关联将 f.select 更改为带有 has_many 的复选框
问题描述
是否可以使用练习中的 new_form 在连接模型表中生成多行?该代码仅在创建单个练习时有效,该练习链接到 body_section 然后选择现有肌肉。
我试图将代码更改为使用 check_box 但失败了
原始代码
运动模型
has_many :body_sections
has_many :muscles, through: :body_sections
accepts_nested_attributes_for :body_sections
end
肌肉模型
has_many :body_sections
has_many :exercises, through: :body_sections
body_section.model
belongs_to :muscle
belongs_to :exercise
accepts_nested_attributes_for :exercise
end
运动控制器
def new
@exercise = Exercise.new
@exercise.body_sections.build
@muscles = Muscle.all
end
# private method for strong parameter
params.require(:exercise).permit(:name, :note, :body_sections_attributes => [:name, :muscle_id])
为复选框修改
练习_form.view
<div>
<%= exercise_form.label :name, "Exercise Name" %>
<%= exercise_form.text_field :name %>
</div>
<div>
<%= exercise_form.fields_for :body_sections do |body_form| %>
<%= body_form.label :name, "Body Section Common Name" %>
<%= body_form.text_field :name %>
<br>
<%= body_form.collection_check_boxes(:muscle_ids, @muscles, :id, :name) do |c| %>
<%= c.label { c.check_box } %>
<% end %>
<% end %>
</div>
运动控制器
# private method for strong parameter
params.require(:exercise).permit(:name, :note, :body_sections_attributes => [:name, :muscle_ids => []])
我收到一个未定义的方法“muscle_ids”错误,显然body_section 没有属于它的muscle_ids 方法。我应该如何修改代码以便能够使用复选框同时在 body_sections 中选择和创建多行?
解决方案
一个身体部分只能有一块肌肉与之相关。
我会使用cocoon来添加/删除正文部分的动态嵌套字段。
然后collection_check_boxes :muscles_ids
,我会使用body_form.select options_from_collection(@muscles)
.
对我来说似乎更合乎逻辑:
Exercise has many ExerciseMuscles
ExerciseMuscles belongs to Exercise
ExerciseMuscles belongs to Muscle
Muscle belongs to BodySection
BodySection has many muscles
这样,您可以创建肌肉/身体部分,然后人们在表格中关联锻炼使用的肌肉(这样您也可以访问锻炼有许多身体部分(通过肌肉))。
推荐阅读
- jquery - 基于 Jquery 行索引的选择列表填充
- python - 视差图数组中的点云
- github - 如何在 Ansible 剧本中从 github 检索和使用 tar.gz.asc?使用给定的 gpg 密钥?
- openstack - 60 秒后未找到按主机名注册的服务 - Openstack/devstack 部署失败
- javascript - 如何在单页中使用 php 从 while 循环中生成多个阅读更多按钮?
- android - 使用recycleView时如何在滑动时删除文本
- c - 查找数组中的重复项数
- ansible - 有没有办法将复杂(嵌套)变量放入 ansible 库存中
- dependency-injection - NestJS动态模块中始终未定义“请求”对象
- python - 使用python在数据库中存储动态列表/数组