2012-01-04 141 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