Using now() to determine what should be displayed


#1

I’m trying to create a paginated list that will take note of the
“end_date” field in my table. This is what I have:

@post_pages, @posts = paginate(:posts, :per_page => 10, :order_by =>
‘end_date’)

in the controller. And for the view:

Posts ending soon

    <% for post in @posts do %> Post Title: <%= post.title %> Date Ending: <%= post.end_date %> <%= link_to 'View this post', :action => 'show', :id => post %> <% end %>

Everything works great. But, I would like anything with an “end_date”
before today to not be displayed. I’m assuming I need to weasel now() in
there someplace, but I can’t figure out where.


#2

I also tried:

@ending = Post.find(:all, :conditions => “end_date <= now()”)
@post_pages, @ending = paginate(:posts, :per_page => 10, :order_by =>
‘end_date’)

in the controller, no luck.


#3

Hi,

2006/6/14, Jasbur removed_email_address@domain.invalid:

@post_pages, @posts = paginate(:posts, :per_page => 10, :order_by =>
‘end_date’)

@post_pages, @posts = paginate(:posts, :per_page => 10, :conditions
=> ‘end_date >= NOW()’:order_by => ‘end_date’)

Your other solution would not work because you’d be creating a
separate array. If you were to check log/development.log you’d see
the two queries.

Hope that helps !


#4
  1. In your controller add conditions to the paginate call:
    @post_pages, @posts = paginate(:posts, :conditons => ‘end_date >
    CURRENT_DATE’,:per_page => 10, :order_by =>
    ‘end_date’)
    —alternatively—
    2)In the view you could do the following:

Posts ending soon

    <% for post in @posts do %> <% if post.end_date > now %> Post Title: <%= post.title %> Date Ending: <%= post.end_date %> <%= link_to 'View this post', :action => 'show', :id => post %> <% end %><% end %>

I like #1 the best it keeps the view as simple.
-Steve
http://www.stevelongdo.com


#5

Jasbur wrote:

I also tried:

@ending = Post.find(:all, :conditions => “end_date <= now()”)
@post_pages, @ending = paginate(:posts, :per_page => 10, :order_by =>
‘end_date’)

Try “end_date => Time.now”

If you need it in a specific Date format, check the method documentation
at
http://api.rubyonrails.org/ for ‘to_date’

hth,
Bill