如何增加新记录的数据

时间:2017-05-28 07:54:43

标签: ruby-on-rails postgresql ruby-on-rails-5 simple-form

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

在创建新记录时,分配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 %>

1 个答案:

答案 0 :(得分:0)

acts_as_list正是您所寻找的,它会优雅地完成它。

如果你不想要宝石依赖,我可以想到两件事,

使用回调:

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

相关问题