Adding an autoincrementing SNO column in Rails Scaffolding?
-
19-09-2019 - |
Question
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?
Solution
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
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow