【发布时间】: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