我创建了一个关联,以减少像这样的构造中的查询数量
@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中,它运行良好。我该如何解决这个问题?
答案 0 :(得分:1)
添加类属性可解决此问题。像这样包括:class => "Post"
:
one_to_one :posts_count, :read_only => true, :key => :id, :class => "Post",
#...