Is there a way in which I can create a serial number (SNO) column through scaffolding in Rails which increases on adding a record, decreases on deleting a record and cannot be modified manually?
A:
If you want to create a summary column on a model you will need to put this logic into your models. There is not a built in method for this (like a standard autoincrement field), but it can be added easily:
class Parent << ActiveRecord::Base
# Contains a field: summary_field
end
class Child << ActiveRecord::Base
after_save => :increment_summary
before_destroy => :decrement_summary
def increment_summary
Parent.find(self.id).summary_field.increment
end
def decrement_summary
Parent.find(self.id).summary_field.decrement
end
end
Mike Buckbee
2009-08-25 14:04:07
+1
A:
It's not clear whether there is any relationship involved, but it sounds like counter_cache may be a good fit.
A Railscast episode provides the code examples and a video tutorial.
Douglas F Shearer
2009-08-25 14:13:42