views:

44

answers:

2

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?

+1  A: 

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.

Yannis
How could that logic look like?
Well, I cannot guess what you are trying to do with the few infos you gave us… Try to update your question and post the code of your model (at least).
Yannis
A: 

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
danengle