D.Graves D.Graves - 1 year ago 49
Ruby Question

Post be up for a limited time?

What I would like is say every monday my index on my homepage that shows all the post gets like reset every monday. The posts still are available on the users profile page but the main homepage they're no longer on there. Im just thinking to keep it clean and everything like that. How would I go about doing this?

Some code from my post controller

def index
@posts = Post.all.order("created_at DESC")

def new
@post = current_user.posts.build

def edit

def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
render :new

My post model

belongs_to :user
has_attached_file :image, :styles => { :medium => "100x100>", :thumb => "300x300>" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]

And my post Index

<div id="posts" class="transitions-enabled">
<% @posts.each do |post| %>
<div class="box panel panel-default">
<%= link_to image_tag(post.image.url(:medium)), post %>
<div class="panel-body">
<strong><%= post.user.username if post.user %></strong><br/>
<%= post.description %>
<% if post.user == current_user %>
<div class="actions">
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
<% end %>

Answer Source

For example you could create Post with expire_date as @tadman proposed in comment. And then just create a scope to get fresh posts.

Here is a code example:

# post.rb
after_create :set_expiration_date

scope :fresh, -> { where("expiration_date > ? ", DateTime.now) }

def self.expire_fresh_posts
  Post.fresh.update_all(expiration_date: DateTime.now)

def set_expiration_date
  # runs only on creating new post, set expiration date after 1 week
  updte_attribute(:expiration_date, DateTime.now + 1.week)

Then you could just show posts that isn't expired

def index
  # other stuff you need to do here
  @posts = Post.fresh

And of you need to expire posts every week you could use sidetiq for it.

class ExpirationWorker
  include Sidekiq::Worker
  include Sidetiq::Schedulable

  recurrence { weekly }

  def perform