Ruby on rails Howto:todays记录的模型范围
哎,, 如何将rails 3中的作用域设置为todays记录 这还不起作用。我没有数据Ruby on rails Howto:todays记录的模型范围,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,哎,, 如何将rails 3中的作用域设置为todays记录 这还不起作用。我没有数据 class MyModel < ActiveRecord::Base scope :today, :conditions => { :created_at => Date.today } end classmymodel{:created_at=>Date.today} 结束 Rails在类级别评估作用域,因此当您使用:conditions=>{:created_at=>Date.
class MyModel < ActiveRecord::Base
scope :today, :conditions => { :created_at => Date.today }
end
classmymodel{:created_at=>Date.today}
结束
Rails在类级别评估作用域,因此当您使用:conditions=>{:created_at=>Date.today}时,它评估Date.today并将所有记录与预评估日期进行比较。要避免这种情况,请使用lamda定义特定于日期或时间的范围
scope :today, lambda { :conditions =>[ "created_at = ? ", Date.today] }
由于“created_at”列包含日期和时间,但您只需要比较日期,所以有两种方法(我假设您使用MySQL):
scope:today,lambda{WHERE(“在{DateTime.now.start\u of_day}和{DateTime.now.end\u of_day}”之间创建的}
scope:today,lambda{WHERE('DATE(created_at)=?',DATE.today)}
def self.up
add_column table_name, :created_on, :date
add_column table_name, :updated_on, :date
end
scope:today,lambda{where(创建于:Date.today)}
我认为您可以定义这样一个通用范围:
class MyModel < ActiveRecord::Base
scope :created_on, lambda {|date| {:conditions => ['created_at >= ? AND created_at <= ?', date.beginning_of_day, date.end_of_day]}}
def self.today
self.created_on(Date.today)
end
end
在我看来,这是最容易理解的方法
def self.created_today
where("created_at >= ? AND created_at < ?", Date.today, Date.tomorrow)
end
def self.created\u今天
其中(“创建时间>=”和创建时间<?”,日期。今天,日期。明天)
结束
我知道这是一个老问题,但仍然可以帮助任何人
这是我解决这个问题的方法:
scope:today,->{where(创建时间:DateTime.now.start\u of_day..DateTime.now.end\u of_day)}
语法错误,意外的tASSOC,期望“}”…今天,lambda{:conditions=>{:created_at=>Date.today}…抓住了要点:“created_at”列包含日期和时间,但我需要只比较日期(day,不含时间)如何告诉rails(rake)创建一个只包含日期的字段?您只需要添加“created_on”和“update_on”字段。这些列名是特殊的,因此值将由Rails自动设置。最终作用域:scope:today,lambda{where(“created_on=?”,Date.today)}从技术上讲,应该是created\u at>=?和created\u at I fixed'>'和'='和'查看文档,回头看,我发现这对我来说更灵活和有用scope:date,->(date){where(created\u at:date.to\u time.start\u of\u day..date to\u time.end\u of\u day)}
def self.created_today
where("created_at >= ? AND created_at < ?", Date.today, Date.tomorrow)
end