Enis D. Enis D. -4 years ago 80
Ruby Question

Making posts inactive after a date and time

I've to make posts inactive after a given date and time by the user who creates these posts. I've added a boolean field "published" to make a post active or unactive.

If the post is active, every visitor will see the post. If it's inactive, the post will be seen in the user dashboard as inactive.

For you guys what is the best way to make a post inactive after the given datetime passed? That should be automatic but I don't think the suitable way is using Active Job and ;


  • Check all posts in the db if active,

  • If active, compare the given datetime and current datetime

  • If needed, make it inactive



I'm using heroku, so that'll make my worker busy all the time.

Answer Source

You can do some things:

Option 1:

Based in the @jawad-khawaja answer, I think a better approach is to use expired_at instead of published_at because for me, a publish date is a date when a post is available for people. This way the user can define an expiration date for his own post (not the same publish date).

Here some example how to you can get active/inactive posts based on its expiration date

# active posts
scope :published, -> { where('expired_at > ?', Time.now) }

# inactive posts
scope :unpublished, -> { where('expired_at < ?', Time.now) }

Option 2:

If you have an attribute published as boolean and you really need mark it automatically, the option is to use whenever gem

CONS for this option:

  • You will have two attributes representing the same thing: published as boolean and expiration_datetime as datetime
  • If the minimum unit for an expiration date is a minute, you need to check every minute if every not-expired post enter to the expired state. And you will have probably an overload for your server.

Conclusion:

My recommended way is to choose the option 1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download