0

我正在使用 gemimpressionist来记录显示操作的页面浏览量。

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

有任何想法吗 ?

提前致谢!

4

4 回答 4

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
于 2014-12-18T14:59:12.893 回答
2

在印象.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到处写子句要好。

于 2014-12-18T15:11:37.603 回答
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)进行比较。

于 2014-12-18T15:02:32.127 回答
0

虽然比我容易

在广告.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
于 2014-12-18T18:55:53.667 回答