例如,我想做类似以下的事情:
class Country has_many :states has_many :citIEs,:through => :states has_many :events,:through => :citIEsendclass State belongs_to :country has_many :citIEs has_many :events,:through => :citIEsendclass City has_one :country,:through => state belongs_to :state has_many :eventsendclass Event belongs_to :city,:counter_cache => true has_one :state,:through => city,:counter_cache => true has_one :country,:through => :state,:counter_cache => true end
因此,我希望能够访问每个城市,每个州以及每个国家/地区的活动数量.
我有城市和州工作,但似乎无法在伟大的祖父母国家模型上运行counter_cache.
我错过了什么吗?这可能吗?有没有更好的方法呢?
我真的很感激社区的一些想法.谢谢!
解决方法 您是否看过计数器缓存railscasts剧集?它可能会有所帮助.http://railscasts.com/episodes/23-counter-cache-column.
如果您只想计算几个级别,可以链接几个语句以获得答案.但是,这不会非常有效,因为要完成此 *** 作的多个DB调用,因此如果您要经常运行此计数,则最好缓存计数.
以下是获取国家/地区所有事件计数的示例(未经测试),例如:
country = Country.find(params[:ID])number_of_events_in_country = 0country.states.each{|s| s.citIEs.each{|c| number_of_events_in_country += c.events.count}}总结
以上是内存溢出为你收集整理的ruby-on-rails – 如何在Rails应用程序中计算伟大的孙子对象?全部内容,希望文章能够帮你解决ruby-on-rails – 如何在Rails应用程序中计算伟大的孙子对象?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)