2012-04-23 45 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 

此代碼只有一個查詢