簡體   English   中英

Rails在include(:children)上的使用范圍

[英]Rails use scopes on includes(:children)

楷模

class User
  has_many :pictures

class Picture 
  belongs_to User
  mount_uploader :picture, UserPictureUploader
  def self.profile
    find_by(is_profile: true)
  end

控制者

User.includes(:pictures).where(...

視圖

=user.pictures.profile.picture_url

這導致以下問題,將再次查詢每張圖片。 如果我們使用user.pictures.where(profile: true).picture_url ,它將不會進行任何新的sql查詢。

題:

我們如何在已經包含的結果中使用作用域?

像下面這樣

class User
  has_many :pictures
  scope :some_name, -> { includes(:pictures).where(your_query_here) }
end

另外, scopes僅在Class上使用(換句話說,它們是class methods ),如果您想在instance上使用它,則需要定義一個實例方法,如下所示

class User
  has_many :pictures

  def some_name
    self.includes(:pictures).where(your_query_here)
  end
end

經過一點挖掘,我發現了這個問題

在Rails 4中相當於has_many'conditions'選項是什么?

看起來您可以將條件放在has_many關系上,實質上就是您要查找的作用域配置。 就像這樣:

has_many :old_pictures, :class_name => 'Picture', 
         :foreign_key => 'picture_id', -> { where('created_at < ?', Time.now - 7.days) } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM