我有优惠券模式,在此模型文件中我有 suitable_for_use 方法。我想列出优惠券如果coupon.suitable_for_use == true 。有什么简短的方法吗?我写了这段代码,但它不起作用。
@coupons = []
coupons = Coupon.all.each do |coupon|
if coupon.suitable_for_use
@coupons << coupon
end
end
@coupons = coupons
proper_for_use方法
def suitable_for_use
result = true
if is_used?
result = false
elsif self.start > Time.now.in_time_zone
result = false
elsif self.end < Time.now.in_time_zone
result = false
end
return result
end
答案 0 :(得分:1)
问题是你为@coupons分配了两次。 each
的返回值是它给出的集合。因此,您的最后一行会重新分配Coupon.all
返回的原始优惠券。
@coupons = Coupon.all.select(&:suitable_for_use)
如果你不确定那是什么,这是扩展版本。
@coupons = Coupon.all.select {|coupon| coupon.suitable_for_select}
基本上,select会占用一个会迭代的块,如果块返回true,那么它会将该元素添加到返回的集合中。因此,任何返回false的优惠券都不会被select返回。
&amp;:suitable_for_use被称为proc的符号。它实际上扩展到第二行中的块,并且在ruby one-liners中很常见。