Thursday, January 29, 2015

Way to use Time and Date in Active Record Association

In Active Record associations we can write conditions also, in that case whenever you are using the association by default the condition also applied.  So it is a good practice to use condition in associations.

see the below example


The above example will return always the published comments for the user.

Problem will come, when you are using Date or Time in the condition.  Because the condition will be loaded at the time of starting your server or console.  So the date and time will be the server start time, and it won't change until you restart the server.  So you won't get expected results.

To avoid that, we should not use date and time in the association condition, we can achieve that by adding scopes with that association.

see the below example

Note: Use lambda or proc in scopes, otherwise the same problem what we trying to resolve will appear again.

No comments:

Post a Comment