Rails找到所有属于另一个资源并与之共享的资源

时间:2014-04-11 15:52:30

标签: ruby-on-rails activerecord

我有一个用户模型has_many:视频。

我希望视频列表包含与他们共享的视频,这由多态共享模型表示,其中可共享类型在此实例中为视频。

我的问题是如何调用user.videos并获取用户拥有并已与他们分享的视频列表?

或者有一种方法可以在User模型上定义:videos_including_shared方法,它们可以用于相同的目的吗?

share.rb

class Share < ActiveRecord::Base

  # The owner of the thing being shared
  belongs_to :shared_by, class_name: "User" # , ploymorphic: true

  # The user with whom the owner has shared the video with
  belongs_to :shared_with, class_name: "User" # , ploymorphic: true

  # The thing being shared
  belongs_to :shareable, polymorphic: true

  ...

user.rb

class User < ActiveRecord::Base

  has_many :videos, -> { order("created_at desc") }, dependent: :destroy

  # Resources that this user has shared
  has_many :shares, dependent: :destroy, foreign_key: "shared_by_id", inverse_of: :shared_by

  # Resources that this user have shared with them
  has_many :reverse_shares, dependent: :destroy, foreign_key: "shared_with_id", class_name: "Share", inverse_of: :shared_with

  # 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"

  ...

video.rb

class Video < ActiveRecord::Base

  has_attached_file :video

  belongs_to  :user
  has_many    :shares, as: :shareable, dependent: :destroy

  ...

修改

似乎替代方法的答案(使用实例方法)看起来像这样(我想......):

def videos_including_shared_with
  videos.merge(videos_shared_with)
end

这很接近但是它返回了一个使用&#34; AND&#34;的where子句。它需要是一个&#34; OR&#34;。所以仍然没有运气,但是我找到了一种方法来实现这一点我仍然希望看到如何使用范围来实现这一点

1 个答案:

答案 0 :(得分:0)

我认为使用&#39;视频&#39;会很难。正如您在编辑中所提到的那样,协会会将您的范围限制为属于该用户的视频。您可以在Video的一个查询中执行此操作,但是:

Video.includes(:shares).where('videos.user_id = ? OR shares.shared_with_id =?', user_id, user_id)

我没有重建你的AR关系结构,但我不知道这应该有用(作为一个警告,我不会使用多态关联因为我是偏执的引用完整性,但对于非多态的我95%确定这会起作用,所以希望它对你的情况有好处。)