Hi,
I have a Pages table in my DB with a field called position.
How can I increase that value by one before it's saved?
Even better how can I remove unused positions and give the new record the correct position number?
Hi,
I have a Pages table in my DB with a field called position.
How can I increase that value by one before it's saved?
Even better how can I remove unused positions and give the new record the correct position number?
You need a before_save callback:
In your Page model:
before_save :increase_position
def increase_position
self.position += 1
end
You can add any kind of logic to the increase_position method to remove unused positions.
you need to use the acs_as_list plugin or setup some before and after filters.
before_create :set_position
after_destroy :fix_positions
def set_position
self.position = Page.count + 1
end
def fix_positions
Page.order('position asc').all.each_with_index do |page, index|
page.update_attribute(:position, index + 1) unless page.position == index + 1
end
end