如何在Rails应用程序中计算伟大的孙子对象?

时间:2012-04-02 13:42:20

标签: ruby-on-rails

任何人都可以帮我计算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。

我错过了什么吗?这可能吗?有没有更好的方法呢?

我真的很感激社区的一些想法。谢谢!

3 个答案:

答案 0 :(得分:2)

您是否看过计数器缓存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}}

答案 1 :(得分:1)

如果是祖父母关系,你可以直接使用has_many(正如你上面列出的那样),但你有一个很好的祖父母关系,但这不适合。

您可以做的一件事(如果您有多个父级子关系级别)将在Country类中放置一个方法来解析它。

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

  def initialize
    @events = Array.new
  end

  def get_events
    self.states.each{|s| s.each{|c| c.each{|e| @events << e }}}
  end

end

然后只需调用get_events方法,将使用与第一条记录关联的所有事件填充事件。

usa = Country.first
usa.get_events
usa.events 

答案 2 :(得分:0)

我一直试图找出答案。只需单击Jeff的答案的RailsCasts链接,然后找到此6 yr old comment

基本上,您可以使用counter_culture gem的多级缓存功能,将其传递给一系列父级,然后返回到顶部,以执行所需的操作。显然,请确保正常添加相应的列。

class Event
  belongs_to :city
  has_one :state, :through => city
  has_one :country, :through => :state

  counter_culture [:city, :state, :country]
end
相关问题