Ruby on Rails - 从最后一个对象增加1

时间:2016-05-31 10:56:38

标签: ruby-on-rails database increment nested-forms

我正在构建一个用户图库应用程序,用户可以在其中创建相册并将图像上传到他们的相册。我正在使用nested forms图片。

在我的images数据库中,我有一个名为sort_order的列。我想使用sort_order来管理排序和显示用户,例如:他看到 3个12 图像,其中 3 是{{1 }和 12 是该相册中的总图像数。

sort_ordersort_orderinteger。我想要的是根据同一专辑中最后一张图片的之前 default: 0,为每张图片增加/ incrementsort_order个。

例如:图片1 会有sort_order图片2 会有之前的图片sort_id sort_order: 1 => +1等等。

以下是我现在使用的代码:

sort_order: 2

这样做的工作却是错误的。

after_create :previous_image

  def previous_image

    img = user.images.order("id ASC")

    img.each do |image|
      image.increment!(:sort_order, self.sort_order + 1)
    end

  end

而不是id sort_order 10 3 11 2 12 1 id: 10,而是获得sort_order: 1

这是日志:

3

它从底部而不是顶部开始。我该如何解决?

如果没有 SQL (0.5ms) UPDATE "images" SET "sort_order" = ?, "updated_at" = ? WHERE "images"."id" = ? [["sort_order", 1], ["id", 398]] user Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 160]] Slide Load (0.1ms) SELECT "images".* FROM "images" WHERE "images"."user_id" = ? ORDER BY id DESC [["user_id", 160]] SQL (0.1ms) UPDATE "images" SET "sort_order" = ?, "updated_at" = ? WHERE "images"."id" = ? [["sort_order", 1], ["id", 399]] SQL (0.1ms) UPDATE "images" SET "sort_order" = ?, "updated_at" = ? WHERE "images"."id" = ? [["sort_order", 2], ["id", 398]] user Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 160]] Slide Load (0.1ms) SELECT "images".* FROM "images" WHERE "images"."user_id" = ? ORDER BY id DESC [["user_id", 160]] SQL (0.1ms) UPDATE "images" SET "sort_order" = ?, "updated_at" = ? WHERE "images"."id" = ? [["sort_order", 1], ["id", 400]] SQL (0.1ms) UPDATE "images" SET "sort_order" = ?, "updated_at" = ? WHERE "images"."id" = ? [["sort_order", 2], ["id", 399]] SQL (0.1ms) UPDATE "images" SET "sort_order" = ?, "updated_at" = ? WHERE "images"."id" = ? [["sort_order", 3], ["id", 398]] 列,还有另一种方法可以做到这一点,我愿意接受。

1 个答案:

答案 0 :(得分:0)

收到表单数据后,将索引(从1开始)添加到images数组中。

考虑到这是您的图像数组:

images = [{name: 'Image 1', data: 123}, {name: 'Image 2', data: 456}]

使用with_index(1)将排序顺序附加到每个元素:

  

images.map.with_index(1).to_a

=> [[{:name=>"Image 1", :data=>123}, 1], [{:name=>"Image 2", :data=>456}, 2]]