-1

I have Classroom model Like:

class Classroom < ApplicationRecord
    has_many :students,dependent: :destroy
end

I have Student model Like:

class Student < ApplicationRecord
    belongs_to :classroom, optional: true
    validate :check_student_limit
    def check_student_limit
        if Student.where(classroom_id: self.classroom_id).count > 4
            self.errors.add(:name, "Over limit of student in classroom")
        end
    end
end

Classroom has_many student so I want to update the selected students classroom.

Suppose I have a classroom with id: 4. Now I select the three students of that classroom which has an id (14,15,16) and I also select the id in which class I want to move these three students. Let's say I want to move these three students in Classroom_id: 5, These three students should move into the classroom 5, and three students delete from classroom 4.

I create a new form for selecting passed students and a new classroom for those students. In my action controller for this form I get the selected students_ids and new classroom id

But now I'm stuck here. How can I insert all these selected students into the selected classroom? I'm troubling here to solve this, please help me if you can.

Here the Images for the reference.

This is how can I selected the students and new classrooms: This is  how can I selected the students and new classrooms

I got the following params in the console: I got the following params in console

Anshul Riyal
  • 123
  • 1
  • 12
  • Can you add the respective controller code and be specific about what error you are getting while doing so ? It will be helpful – Caffeine Coder Jan 30 '20 at 07:43
  • You can use [this](https://stackoverflow.com/questions/27682951/rails-4-nested-form-with-accepts-nested-attributes-for-controller-setup) as an example. – Yakov Jan 30 '20 at 07:51
  • I want to insert the selected students to selected classroom. and I also want to delete the students of previous classroom. How can i do this ??? – bhadresh chotaliya Jan 30 '20 at 08:04
  • I already have one form for creating new classroom In classroom controller – bhadresh chotaliya Jan 30 '20 at 08:07

1 Answers1

1

Advice: You have written too much about your issue which means many people may skip for reason TLDR.

Your real issue is that you have an array of student ids and a new classroom id but you are stuck with how to update them at once i.e. add to new classroom and remove from previous.

You can achieve that by simply changing their classroom_id from x to y in the controller action that you are posting to:

  def update_class
    Student.where(id: params[:student_ids]).update_all(classroom_id: 5)
    # This will move them to classroom 5 and remove from classroom 4.
  end

You only need to use update_all. If there is more to this issue, comment below and I will update the answer.

ARK
  • 772
  • 7
  • 21