【问题标题】:can't change f.select to a check_box with has_many through association无法通过关联将 f.select 更改为带有 h​​as_many 的复选框
【发布时间】:2019-08-26 19:13:39
【问题描述】:

是否可以使用练习中的 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-rails forms checkbox has-many-through


    【解决方案1】:

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

    我会使用cocoon 来添加/删除正文部分的动态嵌套字段。

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2012-02-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2015-08-16
      相关资源
      最近更新 更多