我在一个有多个通过关联的三个模型中,基本上通过会员资格将用户连接到帐户,如下所示:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :memberships
has_many :accounts, :through => :memberships
end
class Account < ActiveRecord::Base
attr_accessible :expiration_date, :name, :status, :url
has_many :memberships
has_many :users, :through => :memberships
has_one :owner, :class_name => "Membership", :conditions => ["role = ?", "Owner"]
has_many :admins, :class_name => "Membership", :conditions => ["role = ?", "Admin"]
has_many :executives, :class_name => "Membership", :conditions => ["role = ? OR role = ?", "Owner", "Admin"]
end
class Membership < ActiveRecord::Base
attr_accessible :account_id, :user_id, :role
validates :role, :uniqueness => { :scope => :account_id }, :if => "role == 'Owner'"
belongs_to :account
belongs_to :user
end
我希望能够通过这些方法Account.first.owner
和. 显然,事实上,我只是获得会员资格。Account.first.admins
Account.first.executives
我可以通过在我的帐户模型上定义新方法来轻松实现这一点,使用类似self.memberships.find_by_role('Owner').user
and self.memberships.find_all_by_role("Admin").collect {|u| u.user}
,但对我来说似乎更草率。有没有办法纯粹通过关联来做到这一点?
非常感谢任何帮助,包括批评我的方法......谢谢!