Ruby Rails - 为相册图片添加排序顺序

Ruby on Rails - Adding sort order to album images

我正在创建一个 用户相册 应用程序。用户可以将许多图像上传到他们的相册中,我正在使用 nested_forms 将图像上传到相册。

在我看来,当用户看到属于相册的图像时,我想显示 X of (total_number_of_images).

例如:如果相册有 12 张图片,而用户在该相册中看到的是 第三张图片,则它将是 3 of 12,当他们点击 next 时,它将变为 4 of 12,等等

请看附件

我怎样才能让它工作?我需要在images-db (如何添加排序顺序)中添加一个column还是有其他方法可以这样做?

这是我到目前为止所做的: 我在 images-db 中添加了一个 sort_order 列并执行此操作:

class Image < ActiveRecord::Base
after_create :previous_slide

@slide = user.images.order("id DESC")
  @slide.find_each do |slide|
   slide.increment!(:sort_order, + 1)
  end

end

这实际上增加了 sort_order column,但顺序错误,因为无论我自己添加了什么,order 总是 id ASC。 我得到:

id    sort
1      4
2      3
3      2
4      1

它必须是:

id    sort
1      1
2      2
3      3
4      4

如您所见,顺序错误。

我认为这段代码有助于解决您的问题

class ImageController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
       @slide = User.images.order(sort_column + " " + sort_direction)
  end


  private

  def sort_column
    User.images.include?(params[:sort]) ? params[:sort] : "name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end

Inapplication_helper.rb

 def sortable(column, title = nil)
      title ||= column.titleize
      css_class = column == sort_column ? "current #{sort_direction}" : nil
      direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
      link_to title, {:sort => column, :direction => direction}, {:class => css_class}
    end