Skip to content

Instantly share code, notes, and snippets.

@Fire-Dragon-DoL
Last active August 29, 2015 14:13
Show Gist options
  • Save Fire-Dragon-DoL/21984f8114c9b7661f49 to your computer and use it in GitHub Desktop.
Save Fire-Dragon-DoL/21984f8114c9b7661f49 to your computer and use it in GitHub Desktop.
ActiveRecord scope eager_loaded table, is it possible?
class Client < ActiveRecord::Base
has_one :user
scope :actives, -> { where(starting_date: a_date, finishing_date: another_date, enabled: true) }
end
# What I would like to write
User.eager_load(:client).connectable.where("client is in :actives scope")
# Current options
# 1 - (but this violates dry)
User.eager_load(:client).connectable.where(['clients.starting_date = ? AND clients.finishing_date = ? AND clients.enabled = ?', a_date, another_date, true).references(:client)
# Other options?
# 2 - My best attempt so far
User.connectable.where(client_id: Client.actives.pluck(:id))
class User < ActiveRecord::Base
belongs_to :client
scope :connectable, -> { where.not(access_token: nil, instance_url: nil) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment