2013-02-24 57 views
0

我已经优惠券模式在这个模型文件我有一个suitable_for_use method.I要列出优惠券如果coupon.suitable_for_use ==真。就是有什么短的方式来做到这一点?我写了这段代码,但它不起作用。轨道模型行动检查

@coupons = [] 
coupons = Coupon.all.each do |coupon| 
    if coupon.suitable_for_use 
    @coupons << coupon 
    end 
end 
@coupons = coupons 

suitable_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

你可以粘贴'suitable_for_use'的代码吗? – Cluster 2013-02-24 02:27:52

+0

什么是is_used的代码?我在问,因为这里最好的选择是一个AR范围。 – Cluster 2013-02-24 02:46:36

回答

1

问题是你分配两次@coupons。来自each的返回值是它给出的集合。因此,您的最后一行重新分配了由Coupon.all返回的原始优惠券组。

@coupons = Coupon.all.select(&:suitable_for_use) 

如果你不确定这是什么,这是扩展版本。

@coupons = Coupon.all.select {|coupon| coupon.suitable_for_select} 

基本上,选择需要一个块,它会迭代,如果块返回true,那么它会将该元素添加到返回的集合。所以返回false的任何优惠券都不会被select返回。

&:suitable_for_use被称为过程符号。它从字面上扩展到第二行的区块,在红宝石单行中很常见。

+0

未定义的方法'>'为零:NilClass我得到这个错误。 – 2013-02-24 02:39:14

+0

是您的优惠券之一的“开始”零?您第二次入住的唯一通话位置是合适的。 – Cluster 2013-02-24 02:45:30

+0

我解决了在合适的检查中添加行“elsif self.start.nil?|| self.end.nil?result = false”的问题。谢谢集群 – 2013-02-24 02:49:16