如何在新记录上增加数据

How to increment data on new record

我在 Rails 上 Ruby 并且我有一个名为 position 的整数列。

在创建新记录时,分配一个大于其 table 上的最大值的 position 值的最佳方法是什么?

目前我正在这样做:

# 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 %>

acts_as_list 就是你要找的,它会优雅地完成..

如果你不想gem依赖,我可以想到两件事,

使用回调:

before_create :set_position

private

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

自增

autoincrement 是另一个更好的选择,因为它会在数据库级别自行处理,您不需要打扰自己。在您的模型中创建迁移,

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

更新

尊重输入值,

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

Reference