【问题标题】:Update a new table column incrementing the value in rails 3.2更新一个新的表列,增加 rails 3.2 中的值
【发布时间】:2014-08-24 12:42:17
【问题描述】:

我想对表中的条目进行排序,稍后用户将对其进行重新排序,因此我不想使用 ID。我刚刚添加了 :order 列,这些值目前都为零。我知道我可以使用 update_all 给它们所有相同的值,但是我如何给每一行一个比最后一个高一个的值(例如 1、2、3、4、5、6 等)?

我正在使用 Rails 3.2。

【问题讨论】:

  • 您可以单独循环和更新每一个。或者你为什么不使用他们的 id 值更新字段?

标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2


【解决方案1】:

您需要将 order 字段上传到您的迁移中。如果您有很多记录,请考虑将其包装到事务中:

Class.transaction do
  Class.each_with_index do |record, index|
    # index will start at 0 which is probably not what you want
    record.update_attribute :order, index + 1
  end
end

【讨论】:

  • 是的,我刚刚根据您的建议更新了答案
【解决方案2】:

只是添加到@mdemolin 答案在rails 中我们通常使用seeds 来填充数据库,因此您也可以制作 rake 任务 并在那里更新您的订单值。在您的 db/seeds.rb 文件中,您可以执行以下操作:

users = User.all
users.each_with_index do |user, index|
  user.update_attribute(:order => index+1 )
end

然后在终端中运行 rake db:seed

【讨论】:

  • use seeds to populate database 但 OP 需要更新现有记录。这个案例更多关于迁移。
  • @PhilidorGreen 它也可以在现有记录中工作,毕竟种子文件只是一个 ruby​​ 文件
  • 哦,我没有说它不起作用。但毕竟这不是轨道惯例。
  • @PhilidorGreen 他没有提到任何关于迁移的事情,事实上,如果你看这个问题,它会说 I have just added the :order column and the values are currently all nil 所以他确实想用值填充它
  • 良好实践更新存在迁移记录。就知道了。
猜你喜欢
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2016-05-15
  • 2012-07-29
相关资源
最近更新 更多