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

class User < ActiveRecord::Base
has_many :comments, -> { where(status: 'published') }
end
class Comment < ActiveRecord::Base
belongs_to :user
end
user = User.first
user.comments
view raw blog-2-1.rb hosted with ❤ by GitHub

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

class User < ActiveRecord::Base
has_many :comments, -> { where(status: 'published') }
end
class Comment < ActiveRecord::Base
belongs_to :user
scope :latest, -> { where('created_at > ?', Time.zone.now - 1.week) }
end
user = User.first
user.comments.latest
view raw blog-2-2.rb hosted with ❤ by GitHub
Note: Use lambda or proc in scopes, otherwise the same problem what we trying to resolve will appear again.

No comments:

Post a Comment