0

models

class User
  has_many :pictures

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

controller

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

view

=user.pictures.profile.picture_url

This is causing the following Problem, that each picture will be queried (again). if we use user.pictures.where(profile: true).picture_url it won't make any new sql-queries.

question:

How can we use scopes on the already included result?

Community
  • 1
  • 1
Tim Kretschmer
  • 2,272
  • 1
  • 22
  • 35

2 Answers2

0

Something like below will do

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

Also, scopes are used only on a Class(in other words they are class methods), if you want to use it on the instance, then you need define an instance method something like below

class User
  has_many :pictures

  def some_name
    self.includes(:pictures).where(your_query_here)
  end
end
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • the problem is, that this query isnt working in rails: includes(:pictures).where("user_pictures.is_profile = true") – Tim Kretschmer Sep 17 '15 at 09:43
  • 1
    @huanson You need to append `.references(:user_pictures)` at the end. – Pavan Sep 17 '15 at 09:45
  • `User.includes(:pictures).where("user_pictures.is_profile = true").references(:user_pictures)` then just returns users who have a picture with that flag. but we want to include only those. i guess thats not possible in rails. – Tim Kretschmer Sep 17 '15 at 09:56
  • @huanson What do you mean by but we want to include only those? – Pavan Sep 17 '15 at 10:03
  • we want all users, and including the pictures include(:pictures) where the profile picture (profile: true), so just include 1 picutre, if its there – Tim Kretschmer Sep 17 '15 at 18:11
0

With a little digging I found this question

What is the equivalent of the has_many 'conditions' option in Rails 4?

It looks like you can put conditions on your has_many relation to essentially be the scoped config you're looking for. It'd be something like:

has_many :old_pictures, :class_name => 'Picture', 
         :foreign_key => 'picture_id', -> { where('created_at < ?', Time.now - 7.days) } 
Community
  • 1
  • 1
AJFaraday
  • 2,411
  • 1
  • 16
  • 39
  • 1
    Well it does, if you set this up then use includes(:old_pictures), it should eager-load the scoped version of pictures and not have to re-load them when they're used. (Of course, the query you're making will be different, this is an example) – AJFaraday Sep 17 '15 at 09:59