mardi 20 décembre 2016

Two has_many relationship through same model

I'm facing a problem that I'm not figuring out how to solve it.

I have three models

  • Teacher
  • Rooms
  • Hours

I need to associate them through the same model. By now I have a 4th model called schedules which I have two foreign keys. teacher_id and hour_id, which is working perfectly, but I also need to associate rooms through this model.

Here is my code:

teacher.rb

class Teacher < ApplicationRecord
  scope :active, -> {where(deleted_at: nil)}
  has_many :schedules, dependent: :destroy
  has_many :lesson_hours, through: :schedules
  has_many :teacher_courses, dependent: :destroy
  has_many :courses, through: :teacher_courses
  has_many :registrations

  def check_associations
    errors.add(:base, "Há matrículas cadastradas com esse professor. Por favor ajuste antes de deletar.") if self.registrations.active.count > 0
    return errors.blank?
  end

  def delete!
    if check_associations
      self.deleted_at = Time.current
      save!
      return true
    else
      return false
    end
  end
end

room.rb

class Room < ApplicationRecord
  scope :active, -> {where(deleted_at: nil)}
  has_many :room_courses, dependent: :destroy
  has_many :courses, through: :room_courses
  has_many :registrations

  def check_associations
    errors.add(:base, "Há matrículas cadastradas com essa sala. Por favor ajuste antes de deletar.") if self.registrations.active.count > 0
    return errors.blank?
  end

  def delete!
    if check_associations
      self.deleted_at = Time.current
      save!
      return true
    else
      return false
    end
  end
end

lesson_hour.rb

class LessonHour < ApplicationRecord
  scope :active, -> {where(deleted_at: nil)}
  has_many :schedules, dependent: :destroy
  has_many :teachers, through: :schedules
  has_many :registrations

  def check_associations
    errors.add(:base, "Há matrículas cadastradas nesse horário. Por favor ajuste antes de deletar.") if self.registrations.active.count > 0
    return errors.blank?
  end

  def delete!
    if check_associations
      self.deleted_at = Time.current
      save!
      return true
    else
      return false
    end
  end
end

schedule.rb

class Schedule < ApplicationRecord
  belongs_to :teacher
  belongs_to :lesson_hour
end

All these associations are being constructed through a form in TeachersController

teachers_controller.rb

def set_lesson_days_and_hours
    @lesson_days = LessonHour.select(:weekday)
                             .group(:weekday)
                             .order(:weekday)
                             .to_a
    @lesson_hours = {}
    @lesson_days.each do |ld|
      @lesson_hours[ld.weekday] = LessonHour.active
                                            .select(:id, :start_time)
                                            .order(:start_time)
                                            .where(weekday: ld.weekday)
    end
  end

  def teacher_params
    params
      .require(:teacher)
      .permit(:name, :address, :address_number, :address_complement,
              :address_cep, :address_neighborhood, :city, :state, :birthdate,
              :email, :cpf, :rg, :phone, :mobile, :started_date, :bank, :agency,
              :account_number, :gender, lesson_hour_ids: [], course_ids: [])
  end

And the form to link lesson_hour to teacher is the following:

<div class="row teacher-schedule">
    <h4>Disponibilidade</h4>

    <% @lesson_days.each do |ld| %>
    <div class="col-md-2 one-per-line teacher-schedule">
      <span><strong><%= t(:"date.day_names")[ld.weekday] %></strong></span>
      <%= f.collection_check_boxes(:lesson_hour_ids, @lesson_hours[ld.weekday], :id, :start_time) do |check_box| %>
      <%= check_box.label class:"label-checkbox" do %>
      <%= check_box.check_box + check_box.text.strftime("%H:%M") %>
      <% end %>
      <% end %>
    </div>
    <% end %>
  </div>

So, my question is, how can I include room association in schedule model?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire