Rails4:如何设置关联,使一个用户拥有多种资产?
Rails 4: How to set up associations so that a user has many types of assets?
我想设置我的应用程序,使用户拥有许多资产,资产 table 将通过其列 "asset_type" 和 [= 引用其他 table 26=].
每种资产类型都应该有自己的 table 和自己的列。
这应该允许:user.assets.count 获取所有资产类型的计数
还有:
user.images 获取所有图像,其中 id = asset_id(并且 asset_type = "image")。
我查看了多态关联、多重 table 继承、has_many :through 等。我似乎无法弄清楚这一点。
我尝试上传图表,但我没有足够的声誉。
如果之前有人问过这个问题,我提前道歉,也许是我正在搜索的措辞或其他 - 但经过几次尝试后,我一直没有找到这个解决方案。非常感谢任何帮助!
你可以这样做
class User < ActiveRecord::Base
has_many :assets
has_many :images
end
class Asset < ActiveRecord::Base
belongs_to :user
belongs_to :profile, polymorphic: true
end
class Image < Asset
# inherits user, profile and all Asset attributes
end
class ImageProfile < ActiveRecord::Base
has_one :asset, as: :profile, dependent: :destroy
end
所以资产的 STI 当然需要 "type" 列(字符串)。然后,您可以拥有所需的所有类型:图像、视频、文档...
以及每种类型的配置文件的多态关联。 ImageProfile 是图像特定列的 table,您可以为 VideoProfile、DocumentProfile 等创建其他 table。
您可以在此处阅读有关此架构的更多信息http://railscasts.com/episodes/394-sti-and-polymorphic-associations
如果 ImageProfile 有一个列 exif_data,那么您可以通过 image.profile.exif_data 访问它。
要创建新图像,您可以这样做:
@image = current_user.images.new.tap do |image|
image.profile = ImageProfile.new profile_params
end
我想设置我的应用程序,使用户拥有许多资产,资产 table 将通过其列 "asset_type" 和 [= 引用其他 table 26=].
每种资产类型都应该有自己的 table 和自己的列。
这应该允许:user.assets.count 获取所有资产类型的计数
还有: user.images 获取所有图像,其中 id = asset_id(并且 asset_type = "image")。
我查看了多态关联、多重 table 继承、has_many :through 等。我似乎无法弄清楚这一点。
我尝试上传图表,但我没有足够的声誉。
如果之前有人问过这个问题,我提前道歉,也许是我正在搜索的措辞或其他 - 但经过几次尝试后,我一直没有找到这个解决方案。非常感谢任何帮助!
你可以这样做
class User < ActiveRecord::Base
has_many :assets
has_many :images
end
class Asset < ActiveRecord::Base
belongs_to :user
belongs_to :profile, polymorphic: true
end
class Image < Asset
# inherits user, profile and all Asset attributes
end
class ImageProfile < ActiveRecord::Base
has_one :asset, as: :profile, dependent: :destroy
end
所以资产的 STI 当然需要 "type" 列(字符串)。然后,您可以拥有所需的所有类型:图像、视频、文档...
以及每种类型的配置文件的多态关联。 ImageProfile 是图像特定列的 table,您可以为 VideoProfile、DocumentProfile 等创建其他 table。
您可以在此处阅读有关此架构的更多信息http://railscasts.com/episodes/394-sti-and-polymorphic-associations
如果 ImageProfile 有一个列 exif_data,那么您可以通过 image.profile.exif_data 访问它。
要创建新图像,您可以这样做:
@image = current_user.images.new.tap do |image|
image.profile = ImageProfile.new profile_params
end