0

Am trying this out

@user.orders.of(:some_type).for_today

business rule says a user can place single order of any type per day, being applied this through callbacks etc. I know that for_today, I want it to return single object. That means I want to make scope for_today return a single object but not an array. However all followings returns array

1

scope :of, lambda{ |type| where(:order_type => type) }
scope :for_today, where(" created_at BETWEEN ? AND ? ", Date.today, Date.tomorrow)

2

scope :of, lambda{ |type| where(:order_type => type) }
scope :for_today, where(" created_at BETWEEN ? AND ? ", Date.today, Date.tomorrow).limit(1)

3

scope :of, lambda{ |type| where(:order_type => type) }
scope :for_today, where(" created_at BETWEEN ? AND ? ", Date.today, Date.tomorrow).first

and then I do not see any other option calling again first in my code

@user.orders.of(:some_type).for_today.first

I guess, it is correct the way it is working, because developer gets to know that she is fetching out 1st record out, which makes more sense, else there is no way to guess whether it returns array or single object. But still, considering my business rules I would expect that for_today should return single object, and hence wanted to know, is there any way to tell scope that it is going to return single object so do not package it using array.

4

0 回答 0