I have a method in my country.rb where I defined a new method.
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
I got the self.duration result I wanted. But when I ran it, it said
undefined method 'save!' for #<Class:0x111170d10>
I want it to count number of states belong to the country everytime a new state is created. Please advise what to do. Thanks.
Just use
update_columninstead. It skips the callbacks and validations. Here are the docs on update_column.Also,
states.countalready gives you the query to find the states by country. Thehas_many :statesallows you to do this.