Rails 4:如何设置关联以便用户拥有多种类型的资产?

时间:2015-02-22 01:38:26

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

我想设置我的应用程序,以便用户拥有多个资产,资产表将通过它的列" asset_type"引用其他表格。和" asset_id"。

每种资产类型都应该拥有自己的表格。

这应该允许:user.assets.count获取所有资产类型的计数

此外: user.images获取id = asset_id的所有图像(和asset_type ="图像")。

我看过多态关联,多表继承,has_many:through等等。我似乎无法弄明白这一点。

我试图上传图表,但我没有足够的声誉。

如果之前已经提出过这个问题,我会提前道歉,也许是我正在搜索或其他方面的措辞 - 但是经过多次尝试后我找到了这个解决方案非常不成功。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情

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,当然需要一个“类型”列(字符串)。然后,您可以拥有所需的所有类型:图像,视频,文档......

每种类型的配置文件的多态关联。 ImageProfile是Image特定列的表,您可以为VideoProfile,DocumentProfile等创建其他表。

您可以在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