如何使用可选连接检索记录?

时间:2012-04-23 16:51:51

标签: ruby-on-rails activerecord join

我希望为用户检索一组时间记录。查询应返回作用域为公共(即private == false)或private(即private == true)的网络的记录,并且用户具有该时间的Slot记录。

我想用ActiveRecord做这件事,但我找到的唯一方法就是做两个单独的查询。这很好,除了结果是数组而不是ActiveRecord关系阻止chainging等。

有什么建议吗?

class TimeAccessPolicy
  attr_reader :network

  def initialize(network)
    @network = network
  end

  def accessible_times_for(user)
    return [] unless user.is_member_of?(network)
    times = network.times.where(private: false)
    times + network.times.joins(:slots).where(private: true, slots: {user_id: user.id})
  end
end

- 编辑:

class Time < ActiveRecord::Base
  belongs_to :network
  has_many   :slots
  has_many   :participants, through: :slots, source: :user

  # has private boolean
  ...
end

class Network < ActiveRecord::Base
  has_many   :memberships, as: :memberable, dependent: :destroy
  has_many   :users, through: :memberships
  has_many   :times

  ...
end

class Slot < ActiveRecord::Base
  belongs_to :user
  belongs_to :time

  ...
end

1 个答案:

答案 0 :(得分:1)

您可以使用scoped method

像这样:

times = network.times.scoped
# times is still ActiveRecord relation
if private
  times = times.joins(:slots).where(private: true, slots: {user_id: user.id})
else
  times = times.where(private: false)
end

此代码只执行一次查询