-1

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

有什么好的出路吗?

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
4

1 回答 1

0

如果我理解正确的问题并且问题是设施关联,它是通过 master_facilities 或 slave_facilities 关联实现的 - 为什么不将基本行为带到模块/类中并将其包含/继承到将实现设施方法的具体类中不同。

于 2012-07-29T09:06:41.420 回答