On 15 November 2012 09:11, Jim Ruther Nill <[email protected]> wrote:
>
>
>
> On Thu, Nov 15, 2012 at 4:51 PM, Colin Law <[email protected]> wrote:
>>
>> On 15 November 2012 08:09, Mauro <[email protected]> wrote:
>> > On 14 November 2012 22:21, Colin Law <[email protected]> wrote:
>> >> On 14 November 2012 21:07, Mauro <[email protected]> wrote:
>> >>> I have a model Reservation with reserved_from and reserve_to
>> >>> attributes of type date.
>> >>> I want create a scope of all reservations where Date.today is between
>> >>> reserved_from and reserved_to.
>> >>> In the model I've done:
>> >>>
>> >>> def self.today_reservation
>> >>>     find_each do |res|
>> >>>         if (Date.today).between?(res.reserved_from, res.reserved_to)
>> >>>                 return
>> >>>         else
>> >>>                 puts "false"
>> >>>         end
>> >>>     end
>> >>>   end
>> >>>   scope :today_reservations, today_reservation
>> >>>
>> >>> but it doesn't work.
>> >>> If reserved_from is 2012-11-01 and reserved_to is 2012-11-02 and
>> >>> Date.today is 2012-11-14 the method above method return an
>> >>> activerecord relation.
>> >>
>> >> That is not how scopes work.  You need something like (not tested)
>> >> scope :today_reservations, lambda {   where("reserved_from > ? and
>> >> reserved_to <= ?", Date.today,  Date.today ) }
>> >
>> > Without lamda it's the same thing?
>> > scope :today_reservations, where("reserved_from > ? and
>> >> reserved_to <= ?", Date.today,  Date.today ) works the same.
>>
>> No it doesn't.  Well it does today but if you don't restart the server
>> then it won't work tomorrow.  Without the lambda it is determining
>> Date.today only once when it loads that line of code.  You need the
>> lambda so that it recalculates it every time you run the scope.
>
>
> Colin is right but you can also use class methods so you dont have to worry
> about
> adding lambdas
>
> def self.today_reservations
>   where('reserved_from > :date AND reserved_to <= :date', date: Date.today)
> end

Does that have any advantage over using a scope?  It has the
disadvantage that one could not say things like
Reservation.where(some conditions).today_reservations

In fact I think my previous comment only applies to production mode
since the code would be reloaded for each request in development mode
and so all would appear to work well - until deployment that is.  I am
not even sure how to write a test that would fail for the code without
the lambda.

Colin

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to