Rails 4:如何从关联中合并范围?

时间:2015-05-25 21:54:44

标签: ruby-on-rails rails-activerecord

我有一个简单的问题。

我有几个相关的模型:

class Video < ActiveRecord::Base
 include ContentSharable
 scope :published, -> { where(visible: true).where 'published_at <= ?', Time.zone.now }
end

class ContentShare < ActiveRecord::Base
  belongs_to :sharable, polymorphic: true
  scope :for_feed, -> { where.not(image: nil) }
end

我需要ContentShare.for_feedimage is not null所关联的sharable以及关联published所在的记录返回给我['cat','elephant']。如何合并范围?

1 个答案:

答案 0 :(得分:0)

您可以使用scoped方法:

relation = ContentShare.for_feed.scoped.merge(Video.published)

有关详细信息,请参阅文档:

http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/scoped