Rails根据父模型属性过滤子模型的记录

时间:2009-11-06 12:52:48

标签: ruby-on-rails activerecord associations has-many

以下是1对M型号:

class FotoGossip < ActiveRecord::Base
    has_many :uploads
    attr_accessible :published_at, ...
end 

class Upload < ActiveRecord::Base
    belongs_to :foto_gossip
end

现在我希望Uploads.all的条件为:published_at NOT NULL是否对应上传的父模型?

1 个答案:

答案 0 :(得分:7)

只需将其添加到您的上传模型:

named_scope :with_published_foto_gossip, :joins => :foto_gossip, :conditions => "foto_gossips.published_at IS NOT NULL"

然后您可以使用已发布的foto_gossip获取所有上传内容,如下所示:

Upload.with_published_foto_gossip