jeudi 4 avril 2019

problem when creating has_many through association using check_box

Is it possible to generate multiple rows in the joined-model table using the new_form from exercise? The code only works when creating a single exercise, that links to a body_section then selecting an existing muscle.

I tried to change the code to use check_box but failed

Original Code

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

exercise controller

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

Modified for check_box

exercise _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>

exercise controller

# private method for strong parameter 
  params.require(:exercise).permit(:name, :note, :body_sections_attributes => [:name, :muscle_ids => []])

I get an undefined method `muscle_ids' error apparently the body_section does not have muscle_ids methods belongs to it. How should I modify the code to be able to use checkbox to select and create multiple rows in body_sections at the same time??




Aucun commentaire:

Enregistrer un commentaire