Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重構課表查詢 #13

Closed
jhang-jhe-wei opened this issue Sep 4, 2021 · 0 comments
Closed

重構課表查詢 #13

jhang-jhe-wei opened this issue Sep 4, 2021 · 0 comments

Comments

@jhang-jhe-wei
Copy link
Owner

jhang-jhe-wei commented Sep 4, 2021

重構 ORM 查詢規則

課表查詢能找出每週特定日期的所有課程

目前做法

由 course 進行查詢

class Course < ApplicationRecord
  has_many :user_and_course_records, dependent: :destroy
  has_many :course_times, dependent: :destroy
  has_many :users, through: :user_and_course_records
  scope :mon, -> { joins(:course_times).where("section LIKE ?", "週一%").pluck(:name,:section) }
  scope :thus, -> { joins(:course_times).where("section LIKE ?", "週二%").pluck(:name,:section) }
  scope :wed, -> { joins(:course_times).where("section LIKE ?", "週三%").pluck(:name,:section) }
  scope :thur, -> { joins(:course_times).where("section LIKE ?", "週四%").pluck(:name,:section) }
  scope :fri, -> { joins(:course_times).where("section LIKE ?", "週五%").pluck(:name,:section) }
  scope :sat, -> { joins(:course_times).where("section LIKE ?", "週六%").pluck(:name,:section) }
  scope :sun, -> { joins(:course_times).where("section LIKE ?", "週日%").pluck(:name,:section) }
end

重構後做法

由 course_time 進行查詢, ORM 應類似為下方程式碼

class CourseTime < ApplicationRecord
    belongs_to :course

    scope :from_user0, -> (user){ joins(:course).where(course: { users: user }) }
    scope :from_user, -> (user){ joins(course: :users).where(course: { users: user }) }
    scope :from_user2, -> (user){ joins(course: :users).where("users.id = ?", user.id) }
    scope :from_user3, -> (user){ joins(course: :users).where(users: {id: user.id}) }
    scope :from_user32, -> (user){ joins(course: :users).where(user_id: user.id) }
    scope :from_user4, -> (user){ joins(course: :user_and_course_records).where(user_and_course_records: {user_id: user.id}) }
    scope :from_user5, -> (user){ joins(course: {user_and_course_records: :user}).where(user_and_course_records: {user_id: user.id}) }
    scope :mon, -> { preload(:course).where("section LIKE ?", "週一%") }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant