无法通过关联将 f.select 更改为具有 has_many 的 check_box

can't change f.select to a check_box with has_many through association

是否可以使用练习中的 new_form 在连接模型 table 中生成多行? 该代码仅在创建单个练习时有效,该练习链接到 body_section 然后 select 现有肌肉。

我尝试更改代码以使用 check_box 但失败了

原码

exercise.model

  has_many :body_sections
  has_many :muscles, through: :body_sections
  accepts_nested_attributes_for :body_sections
end

muscle.model

  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])

修改为 check_box

运动_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 方法。我应该如何修改代码才能将复选框用于 select 并同时在 body_section 中创建多行??

一个 body 部分只能关联一块肌肉。

我会使用 cocoon 为 adding/removing body 部分设置动态嵌套字段。

然后我会使用 body_form.select options_from_collection(@muscles).

而不是 collection_check_boxes :muscles_ids

对我来说似乎更合乎逻辑:

Exercise has many ExerciseMuscles
ExerciseMuscles belongs to Exercise
ExerciseMuscles belongs to Muscle
Muscle belongs to BodySection
BodySection has many muscles

通过这种方式,您可以创建 muscles/body 部分,然后人们将表格中的锻炼使用了哪些肌肉联系起来(这样您还可以访问锻炼有许多 body 部分(通过肌肉)).