views:

59

answers:

1

Rails - using cookies how to delete record from page after the date expiraton.

It should happen in view page

<% cookies[:time] = {:value =>lead_row.created_at.strftime("%b %d, %Y") , :expires => 5.days.from_now } %>

<% if cookies[:time]==nil %> ...should go to delete page..with out any link... <% end %>

+1  A: 

You don't need to redirect to the delete page to delete an item. A before filter could work.

# application_controller.rb
def destroy_when_cookie_is_nil
  some_record.destroy if cookies[:time].nil?
end

# some controller
before_filter :destroy_when_cookie_is_nil

However deleting a record based on a cookie expiring does not seem like a good solution to me. If you want to remove a record after 5 days I highly recommend not using cookies, but add an expires_at datetime column to your model. You can set this column automatically through a callback.

# in model
before_create :set_expiration
def set_expiration
  self.expires_at = 5.days.from_now
end

You can then add a named scope to your model to fetch the non expired records.

# in model
named_scope :active, lambda { {:conditions => ["expires_at IS NULL OR expires_at >=", Time.zone.now]} }

Then you can call Item.active to only display the non-expired records. If you want to ensure these are removed from the database, setup a cron task to find all expired records and delete them.

ryanb