Active Record搜索条件重复 - 如何避免这种情况?

时间:2012-10-01 13:47:02

标签: ruby-on-rails activerecord

这里有我需要的课程,收集一些关于喜欢,评论,内容,观点的统计数据

class UsersActivityTable

  def initialize(user_ids, content_ids, start_date, end_date)
    @user_ids, @content_ids, @start_date, @end_date = user_ids, content_ids,  start_date,  end_date
  end

  def rows
    @rows ||= @user_ids.map do |user_id|
                OpenStruct.new( :full_name => sum_users(user_id),
                                :contributed => sum_contributed(user_id),
                                :interacted => sum_interacted(user_id)
                              )
               end
  end

  private

  def sum_users(user_id)
    @sum_users ||= Hash[ User.value_of(:id, :first_name, :last_name).map{|usr| [usr[0], "#{usr[1]} #{usr[2]}"] } ]
    @sum_users[user_id]
  end

  def sum_contributed(user_id)
    @sum_contributed ||= Content.where(:user_id => @user_ids, :id => @content_ids)
                                .where('date(created_at) between ? and ? ', @start_date, @end_date)
                                .group(:user_id)
                                .count
    @sum_contributed[user_id].to_i
  end

  def sum_interacted(user_id)
    sum_comments(user_id).to_i + sum_views(user_id).to_i + sum_likes(user_id).to_i
  end

  def sum_comments(user_id)
    @sum_comments ||= Comment.where(:user_id => @user_ids, :content_id => @content_ids)
                             .where('date(created_at) between ? and ? ', @start_date, @end_date)
                             .group(:user_id)
                             .count
    @sum_comments[user_id]
  end

  def sum_likes(user_id)
    @sum_likes ||= Like.where(:user_id => @user_ids, :content_id => @content_ids)
                       .where('date(created_at) between ? and ? ', @start_date, @end_date)
                       .group(:user_id)
                       .count
    @sum_likes[user_id]
  end

  def sum_views(user_id)
    @sum_views ||= View.where(:viewable_type => 'Content', :user_id => @user_ids, :viewable_id => @content_ids)
                       .where('date(created_at) between ? and ? ', @start_date, @end_date)
                       .group(:user_id)
                       .count
    @sum_views[user_id]
  end
end

正如您所看到的,有一些重复:

.where('date(created_at) between ? and ? ', @start_date, @end_date)
.group(:user_id)
.count

我为每个实体执行它。 有没有办法应用条件lambda或什么?

我认为可能 - 在集合实例上定义方法并调用它:

# pseudo code
group_results = lambda{|el| el.where('date(created_at) between ? and ? ', @start_date, @end_date)
                             .group(:user_id)
                             .count }
Content.where(...).tap{|collection| collection.defune_method .... }.group_results

1 个答案:

答案 0 :(得分:1)

有时候,对于非平凡的统计数据,一个返回你想要的东西的find_by_sql比复杂的ruby更有效,甚至可能是更清晰

YMMV当然:))