1

画像付きのアルバムを含むアプリケーションを作成しています。画像がアルバムに追加されたときに、画像の ID を 1 から開始したい。ただし、私の現在の設定では、アルバムごとにリセットされず、アルバムごとに番号が付けられます。

モデル

class Album < ActiveRecord::Base
   attr_accessible :title, :description, :album_id
   has_many :images,  :dependent => :destroy
   validates :title, :description, :presence => true
end


class Image < ActiveRecord::Base
   attr_accessible :title, :description, :picture, :image_id, :album_id, :albumcover
   belongs_to :album
   accepts_nested_attributes_for :album
   mount_uploader :picture, PictureUploader 
end 

イメージコントローラー

class Admin::ImagesController < ApplicationController
    respond_to :html, :json
    def index
        @album = Album.find(params[:album_id])
        @images = @album.images.all
    end
    def new
        @album = Album.find(params[:album_id])
        @image = @album.images.new(params[:id])
    end
    def create
        @album = Album.find(params[:album_id])
        @image = @album.images.new(params[:image]) 
        if @image.save
            flash[:notice] = "Successfully added image!"
            redirect_to [:admin, @album, :images]
        else
            render :action => 'new'
        end
    end
    def show
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
    end
    def edit
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
    end
    def update
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
        if @image.update_attributes(params[:image])
            flash[:notice] = "Successfully updated Image"
            redirect_to [:admin, @album, :images]
        else
            render :action => "edit"
        end
    end
    def destroy
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
        @image.destroy
        @albumid = @album.id
        @id = @image.id
        FileUtils.remove_dir("#{Rails.root}/public/uploads/image/picture/#{@albumid}/#{@id}", :force => true)
        redirect_to admin_album_images_path(@album)
    end

end

各アルバム内で番号を 1 から開始するにはどうすればよいですか?

4

1 に答える 1

0

「画像のIDを1から始めたい」

image_id フィールドは、自動インクリメントの可能性が高いデータベース識別子フィールドです。これは images テーブルの行数に基づいており、画像とアルバムの関連付けとは関係ありません。それに依存するロジックを持つことは、おそらく良い考えではありません。

画像のシリアル番号が必要な理由が気になります。たとえば、アルバム内で画像を並べたい場合、1 つのオプションは次のようになります。

album.images.sort_by(&:created_at)

もう 1 つのオプションは、serial_number という名前の列を Images テーブルに追加して、自分で管理することです。

シリアルナンバーでやりたいことを共有できれば、より良い回答が得られます!

于 2013-03-24T20:12:35.293 に答える