首页 > 解决方案 > 无法通过关联将 f.select 更改为带有 h​​as_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 中选择和创建多行?

标签: ruby-on-railsformscheckboxhas-many-through

解决方案


一个身体部分只能有一块肌肉与之相关。

我会使用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

这样,您可以创建肌肉/身体部分,然后人们在表格中关联锻炼使用的肌肉(这样您也可以访问锻炼有许多身体部分(通过肌肉))。


推荐阅读