加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails应用程序中计算伟大的孙子对象?

发布时间:2020-12-17 02:17:34 所属栏目:百科 来源:网络整理
导读:任何人都可以帮我计算Rails应用程序中的孙子孙记录数量吗? 例如,我想做类似以下的事情: class Country has_many :states has_many :cities,:through = :states has_many :events,:through = :citiesendclass State belongs_to :country has_many :cities h
任何人都可以帮我计算Rails应用程序中的孙子孙记录数量吗?

例如,我想做类似以下的事情:

class Country
  has_many :states
  has_many :cities,:through => :states
  has_many :events,:through => :cities
end

class State
  belongs_to :country
  has_many :cities
  has_many :events,:through => :cities
end

class City
  has_one :country,:through => state
  belongs_to :state
  has_many :events
end

class 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 = 0
country.states.each{|s| s.cities.each{|c| number_of_events_in_country += c.events.count}}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读