【发布时间】:2015-01-12 21:07:26
【问题描述】:
我希望仅使用命名范围来编写此查询。原因很简单,当我改变Client 被视为活动的方式时,我不想到处更改代码(User 被视为可连接也是如此)
这是我的代码
client.rb
class Client < ActiveRecord::Base
has_one :user
scope :actives, -> { where(starting_date: a_date, finishing_date: another_date, enabled: true) }
end
user.rb
class User < ActiveRecord::Base
belongs_to :client
scope :connectable, -> { where.not(access_token: nil, instance_url: nil) }
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)
# 2 - My best attempt so far
User.connectable.where(client_id: Client.actives.pluck(:id))
以及指向GIST 的链接以供参考
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4.1