我在 Rails 中使用 DataMapper,替换 ActiveRecord 并尝试做一些单表继承。问题是,sqlite3 似乎正在奇怪地读取我所有继承的表,因此在尝试在 ruby 中创建该表的实例时出现一些奇怪的错误。
我正在使用一个模型 ServerFile 来表示我想在我的数据库中实例化的任何上传或通用文件。我有另一个模型 Upload,它扩展了它并表示来自用户的 Upload。我还有两个从 ServerFile、Thumbnail 和 UploadThumbnail 扩展的模型,分别表示一个通用的 Thumbnail 和一个用于相应上传的 Thumbnail。
我不断收到的错误是DataObjects::IntegrityError (server_files.upload_id may not be NULL)
当我尝试创建这样的 Upload 实例时:
upload = Upload.new(
filename: uploaded_io.original_filename,
path: path.to_s,
content_type: uploaded_io.content_type,
token: rand_token())
upload.member = @member
upload.title = params[:title]
upload.description = params[:description]
upload.save
这是我的模型:
class ServerFile
include DataMapper::Resource
property :id, Serial
property :token, String, unique_index: true
property :filename, String
property :path, Text, unique: true
property :content_type, Text, length: 5..200
property :type, Discriminator
property :created_on, Date
property :created_at, DateTime
property :updated_on, Date
property :updated_at, DateTime
end
class Upload < ServerFile
property :title, String
property :description, Text
has n, :topics, through: Resource
has n, :subjects, through: Resource
has n, :downloads
has n, :comments, 'UploadComment'
has n, :ratings, 'UploadRating'
belongs_to :member
has 1, :thumbnail, 'UploadThumbnail', required: false
end
class Thumbnail < ServerFile
@@IMAGE_EXTENSIONS = [:'png', :'jpg', :'jpeg', :'gif', :'svg', :'cgm']
validates_with_method :filename, :is_valid_image?
def is_valid_image?
@@IMAGE_EXTENSIONS.each do |ext|
return true if /[\w\d\.\_\-]+\.#{ext.to_s}/ =~ @filename
end
[false, 'Invalide image type.']
end
end
class UploadThumbnail < Thumbnail
belongs_to :upload
end
这是我的表'server_files'的sqlite模式(顺便说一句,当我列出我的表时,其中没有列出'uploads'):
sqlite> .schema server_files
CREATE TABLE "server_files" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "token" VARCHAR(50), "filename" VARCHAR(50), "path" TEXT, "content_type" TEXT, "type" VARCHAR NOT NULL, "created_on" DATE, "created_at" TIMESTAMP, "updated_on" DATE, "updated_at" TIMESTAMP, "title" VARCHAR(50), "description" TEXT, "member_id" INTEGER NOT NULL, "upload_id" INTEGER NOT NULL);
CREATE UNIQUE INDEX "unique_server_files_path" ON "server_files" ("path");
CREATE UNIQUE INDEX "unique_server_files_token" ON "server_files" ("token");