1

我创建了一个关联,以减少这样的构造中的查询数量

@user.all do |user|
  puts "User ##{user.id}, post count: #{user.posts_count}"
end

我的模型:

class User
 one_to_many :posts
 one_to_one :posts_count, :read_only => true, :key => :id,
    :dataset => proc{Post.where(:user_id => :id, :deleted => false).select{count(Sequel.lit("*")).as(count)}},
    :eager_loader => (proc do |eo|
      eo[:rows].each{|p| p.associations[:posts_count] = nil}
      Post.where(:user_id => eo[:id_map].keys, :deleted => false).
        select_group(:user_id).
        select_append{count(Sequel.lit("*")).as(count)}.
        all do |t|
          p = eo[:id_map][t.values.delete(:user_id)].first
          p.associations[:posts_count] = t
        end
      end)

  def posts_count
    super.try(:[], :count) || 0
  end

  # ...
end

升级到续集 4.1.0 后,我得到unitialized constant PostsCount了,而在续集 3.44 中它运行良好。我怎样才能解决这个问题?

4

1 回答 1

1

添加类属性解决了这个问题。像这样包括:class => "Post"

one_to_one :posts_count, :read_only => true, :key => :id, :class => "Post",
#...
于 2013-08-29T14:39:51.410 回答