-1

I'm on Ruby on Rails and I have a integer column called position.

What's the best way to assign a position value which is bigger than the the biggest on its table, when creating a new record?

At the moment i'm doing this:

# db/migrate/entry_migration
create_table :entries do |t|
    t.integer          :position
    #...
end
# app/views/entries/_form
<%= simple_form_for @entry do |f| %>
  <% if @entry.new_record? && @entries.order('position').last.present? %>
    <%= f.input :position, as: :hidden, value: @entries.order('position').last.position + 1 %>
  <% else %>
    <%= f.input :position, as: :hidden %>
  <% end %>
<% end %>
a.barbieri
  • 2,398
  • 3
  • 30
  • 58
  • maybe `SERIAL`izing `position` column might help you. https://www.postgresql.org/docs/9.6/static/datatype-numeric.html#DATATYPE-SERIAL `ALTER TABLE your_table ADD COLUMN position SERIAL` – marmeladze May 28 '17 at 08:07
  • @marmeladze this does the trick, but then would it be possible to change that value when it comes to rearrange entries position? Or am I bound to that initial value? – a.barbieri May 28 '17 at 08:50
  • no you can force values any time you want. but if you give more details, about your table, some seed data, i might propose better solution. either with rails or postgres own itself. – marmeladze May 28 '17 at 08:52

1 Answers1

0

acts_as_list is what you are looking for, it will do it gracefully..

If you don't want gem dependency, there are two things I can think of,

Using callback:

before_create :set_position

private

def set_position
  position = YourModel.order(:position).pluck(:position).last.to_i + 1
end

Autoincrement

autoincrement is another better option since it will take care of itself at db level and you dnt need to bother yourself. In your model create migration,

...
t.integer :position
...
execute "CREATE SEQUENCE your_models_position_seq OWNED BY your_models.position INCREMENT BY 1 START WITH 1"

UPDATE

To respect input value,

position = YourModel.order(:position).pluck(:position).last.to_i + 1 unless position.to_i > 0

Reference

Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36