我想要一个表images(其中包含一个字段file:string),以及类似这个模型结构的东西
class BookCover
mount_uploader :file, BookCoverUploader
end
class Book
has_many :covers, class: 'BookCover'
end
class UserAvatar
mount_uploader :file, UserAvatarUploader
end
class User
has_one :avatar, class: 'UserAvatar'
end
如何实现这一目标,使用什么?单表继承还是多态关联?我想轻松地抓住images某些user或book(例如,删除而不用imageable_id)。你会如何组织表格?
更新
从理论上讲,这应该可行,对吧?
# прием отсюда https://maulanaruby.wordpress.com/2007/02/17/sti-vs-polymorphic-association/
class CreateImages < ActiveRecord::Migration[5.0]
def change
create_table :images do |t|
t.string :file, null: false
t.string :type, null: false
t.integer :source_id, null: false
t.timestamps
end
end
end
class Image < ActiveRecord::Base
end
class Cover < Image
mount_uploader :file, CoverUploader
belongs_to :book, foreign_key: 'source_id'
end
class Avatar < Image
mount_uploader :file, AvatarUploader
belongs_to :user, foreign_key: 'source_id'
end
class Book < ActiveRecord::Base
has_many :covers
end
class User < ActiveRecord::Base
has_one :avatar
end