Reputation: 3216
I'm creating a marketplace app where sellers list items to sell. I expire listings 30 days after they've last been updated using the code below.
in listing model:
def self.not_expired
where('created_at >= ?', Date.current - 30.day)
end
In controller:
def index
@listings = Listing.not_expired
end
The above lets me filter the index pages with listings that have not expired yet. How do I show a message on the show pages on these expired listings? If an expired listing shows up in a google search, when users click to the page, I want a message saying the listing has expired.
I'm looking for some conditional statement to put into either my controller or the show html page.
Upvotes: 1
Views: 717
Reputation: 54882
You can simply do:
# Listing model
def expired?
self.created_at <= 30.days.ago
end
# ListingsController
def show
@listing = Listing.find(params[:id])
end
# listings/show.html.haml
- if @listing.expired?
= "This listing is expired!"
- else
# your logic to display a non-expired listing
Also, I recommend you to use a constant for the number of days before the listing goes expired. It would be easier to change it in your code later.
Something like this would work:
# Listing model
DAYS_BEFORE_EXPIRED = 30
def expired?
self.created_at <= DAYS_BEFORE_EXPIRED.days.ago
end
def self.not_expired
where('created_at >= ?', DAYS_BEFORE_EXPIRED.days.ago)
end
Upvotes: 2
Reputation: 9294
The simplest way to do this would be to make an instance method of the class method you have already:
def expired?
self.created_at <= 30.days.ago
end
Then in your ERB:
<% if @listing.expired? %>
Message indicating the listing has expired
<% else %>
The listing
<% end %>
Upvotes: 2