Skip to content

Commit

Permalink
Avoid two unnecessary queries just to check if an instrument is offline
Browse files Browse the repository at this point in the history
The method #offline? needs to check whether there are any current offline reservations. By refactoring to an association and using #present?, Rails will memoize the association and check without another DB query.
  • Loading branch information
vandrijevik committed Mar 14, 2019
1 parent 4ce1c74 commit 633bb82
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 8 deletions.
2 changes: 1 addition & 1 deletion app/models/concerns/products/scheduling_support.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def next_available_reservation(after: Time.zone.now, duration: 1.minute, options
end

def offline?
offline_reservations.current.any?
current_offline_reservations.present?
end

def offline_category
Expand Down
12 changes: 6 additions & 6 deletions app/models/instrument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ class Instrument < Product

RESERVE_INTERVALS = [1, 5, 10, 15, 30, 60].freeze

# Associations
# -------

has_many :instrument_price_policies, foreign_key: "product_id"
has_many :admin_reservations, foreign_key: "product_id"
has_many :offline_reservations, foreign_key: "product_id"
with_options foreign_key: "product_id" do |instrument|
instrument.has_many :admin_reservations
instrument.has_many :instrument_price_policies
instrument.has_many :offline_reservations
instrument.has_many :current_offline_reservations, -> { current }, class_name: "OfflineReservation"
end
has_one :alert, dependent: :destroy, class_name: "InstrumentAlert"

email_list_attribute :cancellation_email_recipients
Expand Down
2 changes: 1 addition & 1 deletion spec/models/instrument_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@

it "switches the instrument to be online" do
expect { instrument.online! }
.to change { instrument.online? }
.to change { instrument.reload.online? }
.from(false).to(true)
.and change { offline_reservation.reload.reserve_end_at }.from(nil)
end
Expand Down

0 comments on commit 633bb82

Please sign in to comment.