1

私は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}にはもっとずさんなようです。純粋に協会を通じてそれを行う方法はありますか?

私のアプローチを批判することを含め、どんな助けでも大歓迎です...ありがとう!

4

1 に答える 1

0

Rails 3 では、独自のメソッドを定義するだけで、このようなことを非常に効率的に行うことができます。例えば:

class Account < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => memberships

  def owner
    users.where(:role => 'Owner').first
  end

  def admins
    users.where(:role => 'Admin')
  end
end

account.ownerこのコードは、またはを呼び出すだけで使用できますaccount.admins

于 2012-08-03T05:40:03.720 に答える