Reputation: 1117
I am able to pass my model tests with two different approaches. Which is preferable? What approaches can I take to determine which is preferable, or if one is preferable?
def queued_video?(video)
queue_items.where(video: video.id).present?
end
vs
def queued_video?(video)
queue_items.map(&:video).include?(video)
end
Upvotes: 1
Views: 85
Reputation: 8295
I am assuming that queued_items
is an ActivreRecord
query.
I would not prefer the second because it evaluates all queue_items
. The first is more efficient.
You can use any?
instead of present?
to make it feel more natural.
I think your best option is to use the exists?
method of ActiveRecord
def queued_video(video)
queue_items.exists?(video: video.id)
end
which results in a select 1
query
SELECT 1 AS one FROM `table_name` WHERE `table_name`.`video_id` = 123 LIMIT
and does exactly what you need in a more elegant way.
Upvotes: 3