【问题标题】:Rails 4: How to set up associations so that a user has many types of assets?Rails 4:如何建立关联以使用户拥有多种类型的资产?
【发布时间】:2015-02-22 01:38:25
【问题描述】:

我想设置我的应用程序,以便用户拥有许多资产,并且资产表将通过其列“asset_type”和“asset_id”引用其他表。

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

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

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

我查看了多态关联、多表继承、has_many :through 等。我似乎无法弄清楚这一点。

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

如果以前有人问过这个问题,我提前道歉,也许这是我正在搜索的措辞或其他 - 但经过多次尝试,我一直未能成功找到这个解决方案。非常感谢任何帮助!

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 感谢您的快速回复!我再次查看了该视频两次,并尝试按照您描述的方式进行设置;但是,似乎 user.images 返回的是资产记录,而不是配置文件记录。我是否错过了访问个人资料的明显内容?
    • 是的,你有。您不应该访问配置文件记录。您访问图像,当您需要访问特定于配置文件的参数时,您可以通过图像访问它们。
    • 您可能会错过的一点是 Image 具有配置文件关联,因为它从 Asset 继承。
    • 奇怪的是,@image.profile 的资产记录似乎也被返回了。 @image.profile =&gt; #&lt;Image id: 1, user_id: 1, profile_id: 1, profile_type: "Image", created_at: "2015-02-22 08:26:37", updated_at: "2015-02-22 08:34:25"&gt;
    • 你能复制粘贴所有相关类和方法的当前代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多