我使用名为impressionist
的gem来记录show动作的页面视图。
Everythink工作得非常好。我可以获得所有综合浏览量的数量:
@advertisement.impression_count
但现在我希望能够在今天,昨天和本月过滤网页浏览量。
到目前为止,我想出了这个解决方案。
@today = Impression.where( :conditions => { :created_at => Date.today...Date.today+1 }, :impresionable_id =>@advertisement.id)
没有错误。
然后在视图中:
<%= "#{@today} views so far!" %>
给了我#<Impression::ActiveRecord_Relation:0x000000068d46f8>
然后我尝试添加:<%= "#{@today.impression_count} views so far!" %>
给我这个:
undefined method `impression_count'
然后我尝试了:<%= "#{@today.count} views so far!" %>
并且仍然是错误:
Mysql2::Error: Unknown column 'conditions.created_at' in 'where clause': SELECT COUNT(*) FROM `impressions` WHERE (`conditions`.`created_at` >= '2014-12-18' AND `conditions`.`created_at` < '2014-12-19') AND `impressions`.`impresionable_id` = 127
有什么想法吗?
提前致谢!
答案 0 :(得分:2)
@today = Impression.where( :conditions => { :created_at => Date.today...Date.today+1 }, :impresionable_id =>@advertisement.id)
返回#<Impression::ActiveRecord_Relation:0x000000068d46f8>
。
试试这个:
@today = Impression.where(created_at: Date.today...Date.today+1, impresionable_id: @advertisement.id).count
答案 1 :(得分:1)
不需要条件哈希。
today = Date.today
range = today..today.next_day
@imp = Impression.where(created_at: range, impressionable_id: @advertisement.id)
如果@advertisement
可以有展示次数,那么以下情况会更好:
@imp = @advertisement.impressions.where(created_at: range)
然后要计算,你必须:
@today = @imp.count
另外,仅供参考,您可能需要使用DateTime.now
代替Date.today
,因为您要与日期时间字段(即created_at)进行比较。
答案 2 :(得分:1)
在 impression.rb
中添加范围scope :today, -> {where("created_at >= ? AND created_at < ?", Time.now.beginning_of_day, Time.now.end_of_day)}
scope :yesterday, -> {where("created_at >= ? AND created_at < ?", 1.day.ago.beginning_of_day, 1.day.ago.end_of_day)}
scope :this_month, -> {where("created_at >= ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)}
控制器中的:
@today = Impression.today.where(impresionable_id: @advertisement.id)
@yesterday = Impression.yesterday.where(impresionable_id: @advertisement.id)
@this_month = Impression.this_month.where(impresionable_id: @advertisement.id)
您可以在任何需要的地方使用这些范围,按今天,昨天或本月的日期过滤Impressions
。与在任何地方编写where
条款相比,它更好。
答案 3 :(得分:0)
比我想象的要容易
在advert.rb
has_many :impressions, :as=>:impressionable
def view_count_yesterday
impressions.where("created_at >= ? AND created_at < ?", 1.day.ago.beginning_of_day, 1.day.ago.end_of_day).size
end
def view_count_today
impressions.where("created_at >= ? AND created_at < ?", Time.now.beginning_of_day, Time.now.end_of_day).size
# impressionist_count(:start_date => 1.day.ago)
end