开发者

Rails Relationship Help

开发者 https://www.devze.com 2023-02-17 16:28 出处:网络
I have simplified my design to make this question more clear. (Design of models below) What I am trying to do is from a CourseEnrollment get all the PatientCourseSteps for that enrollment only (An en

I have simplified my design to make this question more clear. (Design of models below)

What I am trying to do is from a CourseEnrollment get all the PatientCourseSteps for that enrollment only (An enrollment consists of a patient and a course).

Here is what I have tried:

#Gives me ALL the patient course steps regardless of the course
course_enrollment.patient.patient_course_steps 

#Gives me ALL the patient course steps regardless of the patient
course_enrollment.course.patient_course_steps

Below is the models that are necessary

class CourseEnrollment < ActiveRecord::Base
  belongs_to :patient
  belongs_to :course
end

class Course < ActiveRecord::Base
  has_many :course_steps, :dependent => :destroy
  has_many :steps, :through => :course_steps
  has_many :course_enrollments, :dependent => :destroy
  has_many :patients, :through =>:course_enrollments
  has_many :patient_course_steps, :dependent => :destroy
end

class Patient < ActiveRecord::Base
  belongs_to :user, :dependent => :destroy
  has_many :enrollments, :dependent => :destroy
  has_many :clients, :through => :enrollments
  has_many :course_enrollments, :dependent => :destroy
  has_many :courses, :through => :course_enrollments
  has_many :patient_course_steps, :dependent => :destroy
end

class Step < ActiveRecord::Base
  belongs_to :step_type
  belongs_to :client
  has_one :step_quiz, :dependent => :destroy
  has_one :step_survey, :dependent => :destroy
  has_one :step_text, :dependent => :destroy
  has_one :step_download, :dependent => :destroy
  has_one :step_video, :dependent => :destroy
  has_one :step_presentation, :dependent => :destroy
  has_many :course_steps, :dependent => :destroy
  has_many :courses, :through => :course_steps
  has_many :patient_course_steps, :dependent => :destroy
end



class PatientCourseStep < ActiveRecord::Base
  belongs_to 开发者_C百科:patient
  belongs_to :course
  belongs_to :step
end


What I ended up doing was adding a method to CourseEnrollment named patient_course_steps which queries for what I need.

def patient_course_steps
  PatientCourseStep.where(:patient_id => self.patient_id, :course_id => self.course_id)
end
0

精彩评论

暂无评论...
验证码 换一张
取 消