如何查找记录并创建查询范围

时间:2012-12-20 07:05:50

标签: ruby-on-rails ruby-on-rails-3

我有两个型号

艺术家

class Artist < ActiveRecord::Base
   has_many :photos, :as => :photoable, :dependent => :destroy

   def is_approved?
     self.admin_approve == true
   end
end

照片

  class Photo < ActiveRecord::Base
    belongs_to :photoable, :polymorphic => true
  end

我想找到照片(艺术家照片)admin_approve是真的。我该如何为此编写查询和范围。

提前致谢

2 个答案:

答案 0 :(得分:0)

@jdoe,谢谢,但我按照以下方式完成了

class Photo < ActiveRecord::Base
  belongs_to :photoable, :polymorphic => true
    ...
  scope :approve_artists_photo, joins("Inner Join artists on artists.id = photos.photoable_id AND photos.photoable_type = 'Artist'").where("artists.admin_approved = 1")
end

答案 1 :(得分:-1)

您可以添加范围

class Artist < ActiveRecord::Base
   has_many :photos, :as => :photoable, :dependent => :destroy

   scope :approved, where(:admin_approve => true)

   def is_approved?
     self.admin_approve == true
   end
end

然后将照片作为

Artist.approved.photos