2009-11-25 34 views
0

有沒有可能使用DataMapper創建一個條件關聯?DataMapper有n條件

例如:

我希望用戶有n個應用程序只是如果用戶有屬性:developer => true

是這樣的:

class User 
    include DataMapper::Resource 
    property :id, Serial 
    property :name, String, :nullable => false 
    property :screen_name, String, :nullable => false, :unique => true 
    property :email, String, :nullable => false, :unique => true, :format => :email_address 
    property :password, BCryptHash, :nullable => false 
    property :developer, Boolean, :default => false 

    #The user just gets apps if developer 
    has n :apps #,:conditions => "developer = 't'" 

end 

class App 
    include DataMapper::Resource 
    property :id, Serial 
    property :name, String, :nullable => false 

    belongs_to :user 
end 

我知道,這將有可能通過創建User作爲Developer :: User的子類,並且在該類中使用has n,但我真的很想知道它是否可以直接在關聯聲明上生成它。

當我使用ARn時,另一種方法是擴展關聯並重寫每個動作的方法。

所以擴展模塊上我能有這樣的事情:

module PreventDeveloperActions 
    def new 
    if proxy_owner.developer? 
     super 
    else 
     raise NoMethodError, "Only Developers can create new applications" 
    end 
    end 

# and so on for all the actions ... 
end 

但同樣,我真的想避免使用此解決方案,如果有可能的,只是如果有可能執行快速和容易與DataMapper的:)

由於直接的方法提前

回答

2

此刻,你在關係聲明中包含的條件僅適用於目標。因此,如果目標模型具有:主動屬性,則可以說諸如has n, :apps, :active => true之類的內容。不幸的是,您無法定義僅在源(當前)的當前狀態下才有效的關係。

我正在考慮擴展DM中的查詢邏輯,但我不確定會對代碼產生什麼影響,以及除此之外還會提供哪些額外的功能。這可能是我們在DM 1.0之後解決的問題,因爲它也會影響50多個適配器和插件。

STI通常是我推薦的類似的東西,因爲它可以讓你定義只存在於該類型對象的關係。另一種方法是將關係定義爲正常,將訪問器/增變器方法標記爲私有,然後添加代理方法,其等價於return apps if developer?

+0

嗨丹,非常感謝你的關注和支持,它非常​​感謝:)我會嘗試你提到的這些方法,但我很確定這會解決我的問題:)再次感謝 – zanona 2009-11-30 13:04:39