我正在为用户检索一组时间记录。查询应返回范围为公共(即私有 == false)或私有(即私有 == true)的网络的记录,并且用户具有该时间的 Slot 记录。
我想用 ActiveRecord 来做这件事,但我找到的唯一方法是做两个单独的查询。这很好,除了结果是数组而不是 ActiveRecord 关系防止链接等。
有什么建议么?
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