简体   繁体   中英

rails model action check

I have Coupon model and in this model file I have a suitable_for_use method.I want to list Coupons if coupon.suitable_for_use == true .Is there any short way to do this ? I wrote this code but it doesn't work.

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

suitable_for_use method

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

The problem is your assigning twice to @coupons. The return value from each is the collection it was given. So your last line reassigns the original set of coupons returned by Coupon.all .

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

If your not sure what that does, here's the expanded version.

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

Basically, select takes a block that it will iterate over and if the block returns true then it will add that element to the returned collection. So any coupon that returns false will not be returned by select.

The &:suitable_for_use is called a symbol to proc. It literally expands to the block in the second line and is pretty common in ruby one-liners.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM