Reputation: 1959
This should be very simple. Probably embarrassing myself by asking. :)
Although I'm still new to ruby/rails.
I'd like to break out of a loop if a conditional has been met.
A sale is complete when all items have been sold. I'd like to be able to use sale.is_complete?
.
class Sale < ActiveRecord::Base
has_many :items
def is_complete?
items.each do |item|
# as soon as i encounter an unsold item, i want to return false to is_complete
# item.is_sold? will return true or false
end
end
end
Upvotes: 1
Views: 2088
Reputation: 15965
I don't think you want to loop through each item like that. This will be very inefficient. A better way would be to check the count of unsold items. For instance, let assume that the Items Table
has a column called sold
that stores a true or false value. Then we could do this:
def is_complete?
items.where(sold: false).present?
end
Upvotes: 3
Reputation: 168101
In this case, looping is not the best way.
def is_complete?; items.all?(&:is_sold?) end
Upvotes: 7
Reputation: 1223
Perhaps not so embarrassing:
def is_complete?
items.each do |item|
if not item.is_sold? then return false
end
return true
end
Upvotes: 3