【问题标题】:Rails seemingly complex polymorphic associationRails 看似复杂的多态关联
【发布时间】:2014-04-07 22:14:19
【问题描述】:

我有以下模型:用户、视频和收藏。

集合本质上只是一个文件夹模型,用于将视频分组。

我希望用户能够与其他用户共享视频和收藏集。

我所做的是创建一个看起来像这样的“shares”表:

create_table "shares" do |t|
  t.integer  "shared_by_id",      null: false
  t.integer  "shared_with_id",    null: false
  t.integer  "shareable_id",      null: false
  t.string   "shareable_type",    null: false
  t.datetime "created_at"
  t.datetime "updated_at"
end

  • shared_by:是共享资源的用户的 ID。
  • shared_with:是与他们共享资源的用户的 ID。
  • shareable_id:视频或收藏的 ID
  • shareable_type:指定资源是什么,例如。视频或收藏

我有一个如下所示的 share.rb 模型:

class Share < ActiveRecord::Base
  # The owner of the video
  belongs_to :shared_by, class_name: "User"
  # The user with whom the owner has shared the video with
  belongs_to :shared_with, class_name: "User"
  # The thing being shared
  belongs_to :shareable, ploymorphic: true
  def shareable_type=(klass)
    super(klass.to_s.classify.constantize.base_class.to_s)
  end
end

我目前在我的用户模型中有这个:

has_many :shares, class_name: "User", as: :shared_by, dependent: :destroy
has_many :reverse_shares, class_name: "User", as: :shared_with, dependent: :destroy

我想拥有这些,但我有点困惑如何去做:shared_video:video_shared_with:shared_collections:collections_shared_with

【问题讨论】:

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


    【解决方案1】:

    让它发挥作用的关键是:source_type

    在用户模型 user.rb 中:

      ...
      # Resources that this user has shared
      has_many :shares, dependent: :destroy, foreign_key: "shared_by_id"
      # Resources that this user have shared with them
      has_many :reverse_shares, dependent: :destroy, foreign_key: "shared_with_id", class_name: "Share"
      # Videos which this user has shared
      has_many :shared_videos, through: :shares, source: :shareable, source_type: "Video"
      # Videos which have been shared with this user by other users
      has_many :videos_shared_with, through: :reverse_shares, source: :shareable, source_type: "Video"
      ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      相关资源
      最近更新 更多