【问题标题】:Reset primary id for nested/child resource重置嵌套/子资源的主 ID
【发布时间】:2013-03-24 19:53:59
【问题描述】:

我正在构建一个应用程序,其中包含带有图像的相册。我希望图像的 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 开始?

【问题讨论】:

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


    【解决方案1】:

    “我希望图像的 id 从 1 开始”

    image_id 字段是一个可能会自动递增的数据库标识符字段。它基于图像表中的行数,与图像和相册之间的关联无关。让逻辑依赖于它可能不是一个好主意。

    我很好奇您为什么需要图像的序列号。例如,如果您想在相册中订购图片,一种选择是:

    album.images.sort_by(&:created_at)
    

    另一种选择是在您的图像表中添加一个名为 serial_number 的额外列并自行管理。

    如果您可以通过序列号分享您想要实现的目标,您将获得更好的答案!

    【讨论】:

    • 我希望 id 在每张专辑中重新开始,主要是为了订购。博客文章中的 cmets 也是同样的想法。第一条评论是 id 1,接下来是 id 2,等等……这就是我想要的专辑。在每一个中,第一个图像是 id 1,第二个是 id 2,依此类推。
    • 如果您不想重新组合图像,那么我会使用 CubaLibre 的建议,然后在屏幕上书写时使用 each_with_index 方法。尽量不要用不需要的数据污染数据库。
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多