开发者

How can I define the search scope by "this week" meaning Monday - Friday in Ruby on Rails?

This is an extension of an earlier question. I realized, what I really want is to go to a URL /report/thisweek and it will do a .find (or named_scope) across contact_emails.date_sent where date_sent is between MONDAY and FRIDAY of the week to which Date.today belongs.

In other words, if today is THURSDAY, it will do a search for all emails MONDAY through THURSDAY of this week.

Not sure if this is doable or makes sense, but I think that's what I'd ultimately am trying to do.

Thanks!

EDIT: This is what I tried and I get an undefined local variable error for work_days

class ContactEmail < ActiveRecord::Base
  attr_accessible :contact_id, :email_id, :status, :subject, :body, :date_created, :date_sent

  belongs_to :contact
  belongs_to :email
  belongs_to :user

  named_scope :this_开发者_Python百科week, :conditions => {:date_sent => work_days}

  protected
    # Returns a time range corresponding to work days of current or given time's week
    def work_days(t=Time.now)
      monday_0000 = t.at_beginning_of_week
      friday_2359 = 5.days.since(monday_0000)-1.second
      (monday_0000 .. friday_2359)
    end

end


You could do something along the lines of this:

named_scope :this_week, :conditions => ['date_sent > ? and date_sent < ?', Time.now.at_beginning_of_week, Time.now]

Basically, by using ActiveSupport::CoreExtensions::Time::Calculations you will get new methods for time manipulation.


YourModel < ActiveRecord::Base    
  named_scope :this_week, :conditions => {:date_sent => work_days}

(...)

  protected
    # Returns a time range corresponding to workdays of current or given time's week
    def work_days(t=Time.now)
      monday_0000 = t.at_beginning_of_week
      friday_2359 = 5.days.since(monday_0000)-1.second
      (monday_0000 .. friday_2359)
    end
end

I hope this will help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜