An Item has_many Pieces. I have two methods, one that finds out if the Piece is available and one that finds out if an Item has available pieces.
# in piece.rb
def available?(current_user, piece)
if piece.status == 1
true
elsif piece.status == 2
false
elsif piece.status == 3
true if piece.friend_id == current_user.id
end
end
#in item.rb
def available?(current_user, user, item)
false
item.pieces.each do |piece|
if piece.available?(current_user, piece)
true
end
end
end
My available? method in Item is wrong. I want it to return true if an Item has available pieces, and false if not. Theory behind my code is that the method returns false unless there is a piece that returns true. When I do it in the console all I get are the pieces in a hash, not true or false.
Can anyone solve my problem or tell me a better way to do this?
Use Enumerable#any?:
def available?(current_user, user, item)
item.pieces.any? do |piece|
piece.available?(current_user, piece)
end
end
If you need to check whether item has at least one available piece, the method can look like this:
def available?(current_user, user, item)
item.pieces.each do |piece|
return true if piece.available?(current_user, piece)
end
false
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With