2012-01-04 133 views
0

我在我的country.rb中有一个方法,我定义了一个新的方法。保存在模型中

class Country < ActiveRecord::Base 
    has_many :states, :dependent => :destroy 

    after_save :count_total_states 

    def count_total_states 
    self.duration = State.count(:conditions => { :country_id => self.id }) 
    Country.save!(:duration => self.duration) 
    end 
end 

我得到了self.duration结果我想要的。但是,当我运行它时,它说

undefined method 'save!' for #<Class:0x111170d10>

我希望它计数状态的数量属于国家每次一个新的状态被创建。请告诉我该怎么做。谢谢。

回答

2

改为使用update_column。它跳过了回调和验证。这里是update_column的文档。

此外,states.count已经给你查询按国家查找国家。 has_many :states可以让你做到这一点。

class Country < ActiveRecord::Base 
    has_many :states, :dependent => :destroy 

    after_save :count_total_states 

    def count_total_states 
    update_column(:duration, states.count) 
    end 
end 
+0

为什么我需要做'after_save'的原因是因为我想在确定新状态的时候保存数据,然后再进行计数。如果我在保存之前进行计数,则不包括新状态。 – Victor 2012-01-04 15:58:20

+0

好。我更新了我的例子。 – 2012-01-04 16:00:07

+0

它仍然导致无限循环... – Victor 2012-01-04 16:05:01

0

它必须是这样的:

def count_total_states 
    duration = State.count(:conditions => { :country_id => self.id }) 
    self.save!(:duration => duration) 
end 
+0

此解决方案只是部分正确。看到我的答案。 – Shreyas 2012-01-04 15:54:19

+0

我其实已经试过了。但是我得到了ruby的内存泄漏,它吸走了我所有的免费内存并且没有回应。 – Victor 2012-01-04 15:56:27

+0

这是因为它造成了无限循环。 – Shreyas 2012-01-04 15:58:32

0

一对夫妇的错误在这里。

  1. 保存!是一个实例方法,所以Country.save!不会工作(国家是一类)。
  2. 你打电话保存!在由after_save回调触发的方法中,这将导致无限循环。

一个更好的解决办法是:

class Country < ActiveRecord::Base 
    has_many :states, :dependent => :destroy 

    after_create :count_total_states 

    def count_total_states 
    self.duration = State.count(:conditions => { :country_id => self.id }) 
    self.save   
    end 
end 

当然,在这种情况下使用before_save回调的另一个优点是你节省更多的SQL(更新中...)中那些有可能会发生与after_save。

编辑

I want it to count number of states belong to the country everytime a new state is created. 

在您的方案,给出了上述说法和评论下面你将不得不使用的方法after_create。

+0

我之所以需要这样做的原因'after_save'是因为我想在确定新的状态之前保存数据。如果我在保存之前进行计数,则不包括新状态。 – Victor 2012-01-04 15:58:00

+0

你不能在你的场景中使用after_save,因为正如我所说,它会导致无限循环。我已经更新了我的答案。如果你不想使用after_save,请使用after_create。 – Shreyas 2012-01-04 16:05:21

+0

因此,我可以同时使用'after_create:count_total_states'和'after_update:count_total_states',因为更新实际上会允许添加新状态?其实它是一个嵌套模型。我只是简化它在我的问题。 – Victor 2012-01-04 16:07:13