Rails看似复杂的多态关联

时间:2014-04-07 22:14:20

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

我有以下型号:用户,视频和收藏。

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

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

我所做的是创建一个“ 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

1 个答案:

答案 0 :(得分:0)

使其成功的关键是: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"
  ...