2012-07-29 100 views
-1

我有一个模型有两个has_many关联服务于一个逻辑目的,我想根据一些条件在两者之间交替。我可以有一个方便的方法,但是我不能在has_many中使用它:通过关联。是否有可能在Rails模型中有关联别名?

有没有很好的出路?

UPD:模型的代码:

# encoding: UTF-8 

class User < ActiveRecord::Base 
    set_table_name 'clients' 

    devise(:database_authenticatable, 
     #:registerable, 
     :recoverable, 
     :rememberable, 
     :trackable, 
     :validatable, 
     #:token_authenticatable, 
     #:confirmable, 
     #:lockable 
     #:timeoutable, 
     #:omniauthable 
) 

    def email_required? 
    false 
    end 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible(:email, :login, :password, :password_confirmation, :remember_me, # used by devise 
        :address, :phone, :description) 

    attr_accessible :name, :address, :phone, :description 
    validates :name, :presence => true 

    has_many :slaves, :class_name => 'User', :foreign_key => 'master_id', 
      :inverse_of => :master, :dependent => :destroy 

    belongs_to :master, :class_name => 'User', :foreign_key => 'master_id', 
      :inverse_of => :slaves 

    def slave? 
    master.present? 
    end 

    def master? 
    not slave? 
    end 

    validate :slaves_cannot_have_slaves 

    has_many :master_facilities, :class_name => 'Facility', :foreign_key => 'client_id' 
    has_many :analytics_profiles, :class_name => 'AnalyticsProfile', :foreign_key => 'owner_id', 
           :inverse_of => :owner, :dependent => :destroy 

    has_many :facility_permissions 
    has_many :slave_facilities, through: :facility_permissions, source: :facility, autosave: true 

    has_many :units, :through => :facilities, :foreign_key => 'facility_id' 

    # masters and slaves have different ways of accessing their facilities 
    # BUT! It's not a true association so a lot of code (e.g. draper) will fail 
    def facilities 
    if master? 
     master_facilities 
    else 
     slave_facilities 
    end 
    end 

    def dead_units 
    self.units.keep_if(&:dead?) 
    end 

    private 

    def slaves_cannot_have_slaves 
    unless master? or slaves.empty? 
     errors.add :slaves, 'Slaves cannot have slaves' 
    end 
    end 
end 
+2

你可以更具体 - 可以添加你的模型类的代码? – 2012-07-29 07:29:25

+0

@埃雷确定...... – 2012-07-29 08:57:15

回答

0

如果我理解的问题吧,问题是设施的关联,这是通过master_facilities或slave_facilities协会实施的 - 为什么不采取基本行为出来一个模块/类,并将其包含/继承到您的具体类中,以实现不同的设施方法。

相关问题