1 つの論理的な目的を果たす 2 つの has_many アソシエーションを持つモデルがあり、いくつかの条件に応じて 2 つを交互に使用したいと考えています。そのための便利なメソッドを用意できますが、それを has_many :through アソシエーションで使用することはできません。
いい抜け道ある?
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