Home > database >  i have a HABTM ASSociation In rails with student and Subject..when i Edit Subjects then Not remove S
i have a HABTM ASSociation In rails with student and Subject..when i Edit Subjects then Not remove S

Time:07-28

  def update
    if @student.update(student_params)

      # habtm update method 
      params[:student][:subject_ids].each do |subject_id|
        @student.subjects << Subject.find_by(id: subject_id) if subject_id.present?
      end 
      redirect_to students_path 
    else
      respond_to do |format|
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @student.errors, status: :unprocessable_entity }
      end
    end
  end

CodePudding user response:

Your code handles data coming in from a form. I guess you have a list of checkboxes there? To select all the subjects?

You code goes through all the selected subjects and adds them.

It does not ever remove a subject.

Maybe as a first step you could remove all the subjects, and only add them back in if they were selected?

# habtm update method 
@student.subjects = []
params[:student][:subject_ids].each do |subject_id|
  @student.subjects << Subject.find_by(id: subject_id)
end 

CodePudding user response:

Very hard to know for sure what you're asking here, but is this what you're after:

  @student.subjects = Subject.where(id: params[:student][:subject_ids])
  • Related