2012-04-23 51 views
1

我正在寻找为用户检索一组时间记录。该查询应该返回记录范围为公共(即private = false)或私人(即private = true)的网络,并且该用户具有该时间的槽记录。如何使用可选连接检索记录?

我想用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 
+0

你能张贴小更多的背景下,我认为你想添加一些范围到你的模型。发布网络模型,解释时间来自何处,它是网络模型中的一个has_many关系吗?每当我听到'保留ActiveRecord关系'时,我立即想到范围。 – RadBrad 2012-04-23 17:09:56

回答

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 

此代码只有一个查询