在Ruby on Rails中通过连接表选择记录

3

我有三个模型

class Collection < ActiveRecord::Base
  has_many :presentations
  has_many :galleries, :through => :presentations
end

class Gallery < ActiveRecord::Base    
  has_many :presentations
  has_many :collections, :through => :presentations
end

class Presentation < ActiveRecord::Base
  belongs_to :collection
  belongs_to :gallery 
end

如何获取所有不属于给定画廊的集合?

我的SQL知识很基础。我还想让Rails(2.3)不使用显式的SQL表达式完成这项工作。

1个回答

1

从技术上讲,您必须编写一些SQL(where子句)...

gallery_to_exclude = Gallery.first
Collection.find(:all,
  :include => :presentations,
  :conditions => ['presentations.gallery_id IS NULL OR presentations.gallery_id != ?',
                   gallery_to_exclude.id])

如果你想使用Searchlogic,你可以避免这个问题:

Collection.presentations_gallery_id_is_not(gallery_to_exclude.id).all

谢谢,可以用。但是只适用于拥有图库的集合。那么对于没有图库的集合呢?(collection.galleries.length == 0) - 54v054r3n
我编辑了上面的内容,以显示没有画廊的集合。(使用 #find 方法,而不是 searchlogic 方法) - Dave Pirotte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接