D.Graves D.Graves - 6 months ago 15
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")
end

def new
@post = current_user.posts.build
end

def edit
end

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


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?' } %>
</div>
<% end %>
</div>
</div>
<% end %>
</div>

Answer

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)
end

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

Then you could just show posts that isn't expired

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

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
    Post.expire_fresh_posts
  end
end