Created
December 1, 2021 06:21
-
-
Save dorianmariecom/70dc2b2aaedd2f9f79500837e6dc5228 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "bundler/inline" | |
| gemfile(true) do | |
| source "https://rubygems.org" | |
| gem "rails" | |
| gem "sqlite3" | |
| end | |
| require "active_record" | |
| require "logger" | |
| ActiveRecord::Base.establish_connection( | |
| adapter: "sqlite3", | |
| database: ":memory:" | |
| ) | |
| ActiveRecord::Base.logger = Logger.new(STDOUT) | |
| ActiveRecord::Schema.define do | |
| create_table :users do |t| | |
| t.datetime :discarded_at | |
| end | |
| create_table :events do |t| | |
| t.references :user | |
| t.datetime :discarded_at | |
| end | |
| create_table :attendances do |t| | |
| t.references :user | |
| t.references :event | |
| end | |
| create_table :approvals do |t| | |
| t.string :status | |
| t.references :user | |
| t.references :event | |
| t.datetime :discarded_at | |
| end | |
| end | |
| class ApplicationRecord < ActiveRecord::Base | |
| self.abstract_class = true | |
| scope :kept, -> { where(discarded_at: nil) } | |
| end | |
| class User < ApplicationRecord | |
| has_many :events | |
| has_many :approvals | |
| has_many :attendances | |
| end | |
| class Event < ApplicationRecord | |
| default_scope { distinct } | |
| belongs_to :user | |
| has_many :approvals | |
| has_many :attendances | |
| scope :approved, | |
| -> { | |
| joins(:approvals).where(approvals: { status: :approved }) | |
| } | |
| scope :attended_by, | |
| lambda { |user| | |
| joins(:attendances).where(attendances: { user_id: user.id }) | |
| } | |
| end | |
| class Attendance < ApplicationRecord | |
| belongs_to :user | |
| belongs_to :event | |
| end | |
| class Approval < ApplicationRecord | |
| belongs_to :user | |
| belongs_to :event | |
| end | |
| user = User.create! | |
| scope = Event.kept | |
| scope = scope.approved.or(scope.where(user: user)) | |
| scope = scope.attended_by(user).or(scope.where(user: user)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment