私は3つのモデルを持っており、多くのスルーアソシエーションがあり、基本的に次のようなメンバーシップを介してユーザーをアカウントに接続します。
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
とのようなものを使用して、アカウントモデルで新しいメソッドを定義することで、これを簡単に実現できますが、私self.memberships.find_all_by_role("Admin").collect {|u| u.user}
にはもっとずさんなようです。純粋に協会を通じてそれを行う方法はありますか?
私のアプローチを批判することを含め、どんな助けでも大歓迎です...ありがとう!