我如何优化SQL查询,无视这样的情况:
How I can optimise my SQL queries, to ignore situations like this:
Meeting.find(5).users.size => SELECT COUNT(*)FROM ... WHERE ...
Meeting.find(5).users.size => SELECT COUNT(*) FROM ... WHERE ...
User.find(123).meetings.size => SELECT COUNT(*)FROM ... WHERE ...
User.find(123).meetings.size => SELECT COUNT(*) FROm ... WHERE ...
我不知道如何counter_cache在这里使用。
I have no idea how to use counter_cache here.
下面是我的模型关系:
class Meeting < ActiveRecord::Base
has_many :meeting_users
has_many :users, :through => meeting_users
end
class User < ActiveRecord::Base
has_many :meeting_users
has_many :meetings, :through => meeting_users
end
class Meeting_user < ActiveRecord::Base
belongs_to :meeting
belongs_to :user
end
什么是最优化的解决方案?
What are the most optimal solutions ?
和如何在这里实现counter_cache?
And how implement counter_cache here ?
据我知道你无法通过使用 counter_cache
与
的关联,这就是为什么你要手动增加它。
As far as I know you can't use counter_cache
with through
associations, that's why you should manually increment it.
例如(未经测试):
class MeetingUser < ActiveRecord::Base
...
after_create { |record|
Meeting.increment_counter(:users_count, record.meeting.id)
}
after_destroy { |record|
Meeting.decrement_counter(:users_count, record.meeting.id)
}
end
上一篇:如何以编程方式获得Admob的设备ID?方式、设备、Admob、ID
下一篇:以下类不能被实例化: - com.google.ads.AdView Admob的实例、com、google、Admob