2009-07-22 34 views
2

我有了一個模型類,其中包括:曬我的has_many在Rails的

class Group < ActiveRecord::Base 
    has_many :subscriptions 
    has_many :users, :through => :subscriptions 

    has_many :admins, :through => :subscriptions, :source => :user, :conditions => "subscriptions.role = #{ROLES[:admin]}" 
    has_many :subscribers, :through => :subscriptions, :source => :user, :conditions => "subscriptions.role >= #{ROLES[:subscriber]}" 
    has_many :authors, :through => :subscriptions, :source => :user, :conditions => "subscriptions.role >= #{ROLES[:author]}" 
    has_many :pending_subscribers, :through => :subscriptions, :source => :user, :conditions => "subscriptions.pending = true" 
end 

次重複:through => :subscriptions, :source => :user數量困擾我。我知道路線文件,你可以做map.with_options。對於我的模型關聯有沒有類似的東西?

回答

10

with_options實際上是對Object的擴展,所以你可以在你的ActiveRecord::Base使用它,以及

with_options :through => :subscriptions, :source => :user do |obj| 
    obj.has_many :admins, :conditions => "subscriptions.role = #{ROLES[:admin]}" 
    obj.has_many :subscribers, :conditions => "subscriptions.role >= #{ROLES[:subscriber]}" 
    obj.has_many :authors, :conditions => "subscriptions.role >= #{ROLES[:author]}" 
    obj.has_many :pending_subscribers, :conditions => "subscriptions.pending = true" 
end 
+0

這個工作很好,謝謝! – 2009-07-23 13:50:00

2

您可以創建一個調用has_many並具有常用條件的方法。下面是了一個塊乾燥的一種方法:

{ :admins => "subscriptions.role = #{ROLES[:admin]}", 
    :subscribers => "subscriptions.role = #{ROLES[:subscriber]}", 
    :authors => "subscriptions.role >= #{ROLES[:author]}", 
    :pending_subscriptions => "subscriptions.pending = true" }.each do |property, condition| 
    has_many key, :through => :subscriptions, :source => :user, :conditions => condition 
end